Home

Windows Controls: The Open File Dialog Box

Introduction to the Open File Dialog Box

Description

Besides saving files, another common operation performed by users consists of opening files. This refers to existing files since a file must primarily exist. To support this operation, Microsoft Windows provides a standard object: the Open File dialog box:

Description of the Open File Dialog Box

Practical LearningPractical Learning: Introducing File Processing Accessories

  1. Start Microsoft Visual Studio
  2. To create a new application, on the main menu, click File -> New Project...
  3. Select Windows Forms Application
  4. Set the Name to ClarksvilleIceCream3
  5. Click OK
  6. To create a new form, on the main menu, click Project -> Add Windows Form...
  7. In the Add New Item dialog box, set the name of the form to Calculation, and click Add
  8. Design the new form as follows:
     

    Clarksville Ice Scream - Difference Calculation

    Control Name Text Additional Properties
    Label Label   Order Total:  
    TextBox ListBox txtOrderTotal 0.00 TextAlign: Right
    Modifier: Public
    Label Label   Amount Tended:  
    TextBox ListBox txtAmountTended 0.00 TextAlign: Right
    Button Button btnCalculate Calculate  
    Label Label   Difference:  
    TextBox ListBox txtDifference 0.00 TextAlign: Right
    Button Button btnClose Close  
  9. Double-click the Calculate button
  10. 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");
    }
  11. Return to the Calculation form
  12. Double-click the Close button
  13. Implement the event as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  14. In the Solution Explorer, right-click Form1.cs and click Rename
  15. Type ClarksvilleIceCream.cs and press Enter
  16. Right-click the form and click Properties
  17. In the Properties window, change the form's Text to Clarksville Ice Cream
  18. Design the form as follows:

    Clarksville Ice Cream: Form Design

    Control Name Text Additional Properties
    GroupBox   grpIceCream    
    Label Label   Order Date:  
    TextBox ListBox txtOrderDate    
    Label Label   Order Time:  
    TextBox ListBox txtOrderTime    
    Label Label   Flavor:  
    TextBox ListBox txtFlavor    
    Label Label   Container:  
    TextBox ListBox txtContainer    
    Label Label   Ingredient:  
    TextBox ListBox txtIngredient    
    Label Label   Scoops:  
    TextBox ListBox txtScoops 1 TextAlign: Right
    Label Label   Order Total:  
    TextBox ListBox txtOrderTotal 0.00 TextAlign: Right
    Button Button btnCalculate Calculate  
    Button Button btnNewOrder New Order  
    Button Button btnMoneyChange Money Change  
    Button Button btnClose Close  
  19. Double-click the Calculate Total button to access its Click event
  20. 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;
    }
  21. Return to the form
  22. 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;
    }
  23. Return to the form
  24. Double-click the Money Change button
  25. 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();
    }
  26. Change the Click events of the Calculate Total  and the New Order buttons as follows:
    private void btnClose_Click(object sender, EventArgs e)
    {
        Close();
    }
  27. On the Toolbox, click MenuStrip and click the form
  28. On the form, click Type Here. Type &File and press the down arrow key
  29. Type E&xit and press Enter
  30. On the right side of File (on the form), click Type Here
  31. Type &Help and press the down arrow key
  32. Type &Contents... and press the down arrow key
  33. Type &Index... and press the down arrow key
  34. Type &Search... and press Enter
     
    Ice Cream
  35. On the form, click File and double-click Exit
  36. Implement its event as follows:
    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Close();
    }
  37. To save the application, on the main menu, click File -> Save All
  38. Accept the default location and the name. Click Save
  39. To test the application, on the main menu, click Debug -> Start Debugging
  40. Close the form and return to Visual Studio
  41. In the Toolbox, click Dialogs
  42. Click SaveFileDialog SaveFileDialog and click the form
  43. In the Properties window, click (Name) and type dlgSaveFile
  44. Under the form, make sure dlgSaveFile is selected.
    In the Properties window, click Title and type Save an Ice Cream Order
  45. Under the form, make sure dlgSaveFile is selected.
    In the Properties window, click Filter and type
    Clarksville Ice Cream File (*.cic)|*.cic| All Files (*.*)|(*.*)
  46. 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 OpenFileDialog 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;
    }
}

Practical LearningPractical Learning: Introducing the Open File Dialog Box

  1. In the Toolbox, click Dialogs
  2. Click OpenFileDialog Open File Dialog and click the form
  3. In the Properties window, click (Name) and type dlgOpenFile
  4. 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|";
}

Practical LearningPractical Learning: Specifying the Filter

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;
}

Open

On the other hand, when the user selects a file to open, you can check the value of the ReadOnlyChecked property. If it is true, this indicates that the user had clicked the Open As Read-Only check box.


Home Copyright © 2010-2020, FunctionX