Windows Controls: The Open File Dialog Box
Besides saving files, another common operation performed by users consists of opening files. This refers to existing files since a file must primarily…
Introduction to the Open File Dialog Box#
Description#
In addition to saving data, users frequently need to open pre-existing files. To facilitate this, Microsoft Windows includes a built-in Open File dialog box:
Application: Introducing File Processing Accessories
- Start Microsoft Visual Studio
- To create a new application, on the main menu, click File -> New Project...
- Select Windows Forms Application
- Set the Name to ClarksvilleIceCream3
- Click OK
- To create a new form, on the main menu, click Project -> Add Windows Form...
- In the Add New Item dialog box, set the name of the form to Calculation , and click Add
- Design the new form as follows: Control Name Text Additional Properties Label Order Total: TextBox txtOrderTotal 0.00 TextAlign: Right Modifier: Public Label Amount Tended: TextBox txtAmountTended 0.00 TextAlign: Right Button btnCalculate Calculate Label Difference: TextBox txtDifference 0.00 TextAlign: Right Button btnClose Close
- Double-click the Calculate button
- Implement the Click event as follows: private void btnCalculate_Click(object sender, EventArgs e) { double totalOrder, amountTended = 0.00, difference; // Get the value of the total order. Actually, this value // will be provided by the main form totalOrder = double.Parse(this.txtOrderTotal.Text); try { // The amount tended will be entered by the user amountTended = double.Parse(this.txtAmountTended.Text); } catch (FormatException) { MessageBox.Show("The amount you entered is not " + "valid - Please try again!"); } // Calculate the difference of both values, assuming // that the amount tended is higher difference = amountTended - totalOrder; // Display the result in the Difference text box txtDifference.Text = difference.ToString("F"); }
- Return to the Calculation form
- Double-click the Close button
- Implement the event as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
- In the Solution Explorer, right-click Form1.cs and click Rename
- Type ClarksvilleIceCream.cs and press Enter
- Right-click the form and click Properties
- In the Properties window, change the form's Text to Clarksville Ice Cream
- Design the form as follows: Control Name Text Additional Properties GroupBox grpIceCream Label Order Date: TextBox txtOrderDate Label Order Time: TextBox txtOrderTime Label Flavor: TextBox txtFlavor Label Container: TextBox txtContainer Label Ingredient: TextBox txtIngredient Label Scoops: TextBox txtScoops 1 TextAlign: Right Label Order Total: TextBox txtOrderTotal 0.00 TextAlign: Right Button btnCalculate Calculate Button btnNewOrder New Order Button btnMoneyChange Money Change Button btnClose Close
- Double-click the Calculate Total button to access its Click event
- Implement it as follows: private void btnCalculate_Click(object sender, EventArgs e) { double priceContainer = 0.00, priceIngredient = 0.00, priceScoops = 0.00, orderTotal = 0.00; int numberOfScoops = 1; // Find out what container the customer requested // The price of a container depends on which one the customer selected if (txtContainer.Text == "Cone") priceContainer = 0.55; else if (txtContainer.Text == "Cup") priceContainer = 0.75; else priceContainer = 1.15; // If the customer selected an ingredient, which is not "None", add $.95 if (txtIngredient.Text != "None") priceIngredient = 0.95; try { // Get the number of scoops numberOfScoops = int.Parse(this.txtScoops.Text); if (numberOfScoops == 2) priceScoops = 2.55; else if (numberOfScoops == 3) priceScoops = 3.25; else priceScoops = 1.85; } catch (FormatException) { MessageBox.Show("The value you entered for the scoops is not valid" + "\nOnly natural numbers such as 1, 2, or 3 are allowed" + "\nPlease try again", "Clarksville Ice Cream", MessageBoxButtons.OK, MessageBoxIcon.Information); } // Make sure the user selected a flavor, // otherwise, there is no reason to process an order if (txtFlavor.Text != "") orderTotal = priceScoops + priceContainer + priceIngredient; txtOrderTotal.Text = orderTotal.ToString("F"); btnMoneyChange.Enabled = true; }
- Return to the form
- Double-click the New Order button to access its Click event and implement it as follows: private void btnNewOrder_Click(object sender, EventArgs e) { // If the user clicks New Order, we reset the form with the default values txtOrderDate.Text = DateTime.Today.ToShortDateString(); txtOrderTime.Text = DateTime.Now.ToShortTimeString(); txtFlavor.Text = "Vanilla"; txtContainer.Text = "Cone"; txtIngredient.Text = "None"; txtScoops.Text = "1"; txtOrderTotal.Text = "0.00"; btnMoneyChange.Enabled = false; }
- Return to the form
- Double-click the Money Change button
- Implement the Click event as follows: private void btnChange_Click(object sender, EventArgs e) { // Declare a variable for the Calculation form Calculation dlgCalculation = new Calculation(); // Transfer the current value of the Order Total text // box from the main form to the other form dlgCalculation.txtOrderTotal.Text = this.txtOrderTotal.Text; // Display the other form dlgCalculation.ShowDialog(); }
- Change the Click events of the Calculate Total and the New Order buttons as follows: private void btnClose_Click(object sender, EventArgs e) { Close(); }
- On the Toolbox, click MenuStrip and click the form
- On the form, click Type Here . Type &File and press the down arrow key
- Type E&xit and press Enter
- On the right side of File (on the form), click Type Here
- Type &Help and press the down arrow key
- Type &Contents... and press the down arrow key
- Type &Index... and press the down arrow key
- Type &Search... and press Enter
- On the form, click File and double-click Exit
- Implement its event as follows: private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Close(); }
- To save the application, on the main menu, click File -> Save All
- Accept the default location and the name. Click Save
- To test the application, on the main menu, click Debug -> Start Debugging
- Close the form and return to Visual Studio
- In the Toolbox, click Dialogs
- Click SaveFileDialog and click the form
- In the Properties window, click (Name) and type dlgSaveFile
- Under the form, make sure dlgSaveFile is selected. In the Properties window, click Title and type Save an Ice Cream Order
- Under the form, make sure dlgSaveFile is selected. In the Properties window, click Filter and type Clarksville Ice Cream File (*.cic)|*.cic| All Files (*.*)|(*.*)
- Under the form, make sure dlgSaveFile is selected. In the Properties window, click DefaultExt and type cic
The Open File Dialog Box Creation#
To provide file opening support, the .NET Framework provides the OpenFileDialog class which is derived from the FileDialog class that in fact provides most of its functionality. The easiest way to use it is to click the OpenFileDialog button from the Toolbox and click the form. You can click anywhere on the form because the OpenFileDialog object would not be seen at run time. After placing it on the form, you can use the Properties window to configure it.
If you prefer to dynamically create an Open dialog box, declare a variable of type OpenFileDialog and use the new operator to allocate memory using its default constructor. Here is an example:
using System;
using System.Windows.Forms;
public class Exercise : Form
{
private OpenFileDialog ofd;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
ofd = new OpenFileDialog();
}
[STAThread]
public static int Main()
{
Application.Run(new Exercise());
return 0;
}
}Application: Introducing the Open File Dialog Box
- In the Toolbox, click Dialogs
- Click OpenFileDialog and click the form
- In the Properties window, click (Name) and type dlgOpenFile
- Click Title and type Open an Ice Cream Order
Characteristics of an Open File Dialog Box#
The Filename#
One of the most important properties of an Open dialog box is the file it presents to the user. This is represented by the FileName property. If you want a default file to be specified when the dialog box comes up, you can specify this in the FileName property of the Properties window. If you need to use this property, you should make sure the file can be found. If the file is located in the same folder as the application, you can provide just its name. If the file is located somewhere else in the hard drive, you should provide its complete path. Most of the time, you will not be concerned with this property if you are creating an application that will allow the users to open any files of their choice. Once a file is located, it can be accessed using the OpenFileDialog.FileName property.
The Filter#
To make your application more effective, you should know what types of files your application can open. This is taken care of by specifying a list of extensions for the application. To control the types of files that your application can open, specify their extensions using the Filter Property. The Filter string is created exactly like that of a SaveFileDialog control as we saw earlier. Here is an example:
void InitializeComponent()
{
ofd = new OpenFileDialog ();
ofd.Filter = "HTML Files (*.htm)|*.htm|" +
"Active Server Pages (*.asp)|*.asp|" +
"Apache Files (*.php)|*.php|" +
"Perl Script (*.pl)|*.pl|" +
"All Files|";
}Application: Defining the File Filter
- Under the form, make sure dlgOpenFile is selected. In the Properties window, click Filter and type Clarksville Ice Cream File (*.cic)|*.cic| All Files (*.*)|(*.*)
The Filter Index#
Like the SaveFileDialog control, the default extension is the one the dialog box would first filter during file opening. If you want the Open dialog box to easily recognize a default type of file when the dialog box opens, you can specify the extension's type using the DefaultExt property. You can also use the FilterIndex we saw earlier to indicate the default index of the Files of Type combo box.
The Initial Folder#
For convenience, or for security reasons, Open dialog boxes of applications are sometimes asked to first look for files in a specific location when the Open File dialog box comes up. This default folder is specified using the InitialDirectory property.
Showing the Dialog Box#
The essence of using the Open dialog box is to be able to open a file. This job is handled by the ShowDialog() method. Here is an example:
using System;
using System.Drawing;
using System.Windows.Forms;
public class Exercise : Form
{
Button btnOpen;
private OpenFileDialog ofd;
public Exercise()
{
InitializeComponent();
}
void InitializeComponent()
{
ofd = new OpenFileDialog ();
ofd.Filter = "HTML Files (*.htm)|*.htm|" +
"Active Server Pages (*.asp)|*.asp|" +
"Apache Files (*.php)|*.php|" +
"Perl Script (*.pl)|*.pl|" +
"All Files|";
btnOpen = new Button();
btnOpen.Text = "Open";
btnOpen.Location = new Point(12, 12);
btnOpen.Click += new EventHandler(btnWriteClick);
Controls.Add(btnOpen);
}
void btnWriteClick(object sender, EventArgs e)
{
ofd.ShowDialog();
}
[STAThread]
public static int Main()
{
Application.Run(new Exercise());
return 0;
}
}After opening the dialog box, if the user selects a file and clicks OK or presses Enter, the file would be opened.
Opening Various Files#
Most of the time, users are interested in opening one file to view or manipulate. It is also possible for a user to want to select various files and open them at the same time. When the user clicks OK after using the Open dialog box, before taking the next step, you may need to find out whether the user selected various files. To get this information, you can check the value of the OpenFileDialog.Multiselect Boolean property. If the user had selected various files, this property produces a true result. If the user selected only one file, this property renders a false result. The result of this checking process allows you either to agree to open the files or to take some action of your choice.
Opening a File As Read-Only#
After a file has been opened, the user may want to alter it. For example, if it is a text document, the user may want to add and/or delete some words. In some cases, you may want the user to be able to open a file but not to be able to modify it. To provide this restriction, you can set the document as read-only. In some other cases, you may want to let the user decide on this. If you want to give this option to the user, you can start by displaying a read-only check box on the dialog box. To support this, the OpenFileDialog class is equipped with the ShowReadOnly property. If you set it to true, the dialog box would be equipped with an Open As Read-Only check box in its lower section. By default, the Open As Read-Only check box is cleared when the dialog box comes up. The user has the option of keeping it that way or checking it when opening a file. The OpenFileDialog class provides the ReadOnlyChecked property to accompany the read-only option. If you want to display a check mark in the Open As Read-Only check box, you can set the ReadOnlyChecked property to true:
void InitializeComponent()
{
ofd = new OpenFileDialog ();
ofd.Filter = "HTML Files (*.htm)|*.htm|" +
"Active Server Pages (*.asp)|*.asp|" +
"Apache Files (*.php)|*.php|" +
"Perl Script (*.pl)|*.pl|" +
"All Files|";
ofd.ShowReadOnly = true;
ofd.ReadOnlyChecked = true;
}Furthermore, when a file is selected for opening, the ReadOnlyChecked property can be inspected. A value of true signifies that the user opted for the Open As Read-Only setting. Index Copyright © 2010-2011 C#Key

