Home

Windows Controls: The Save Dialog Box

   

Introduction to the Save As Dialog Box

 

Description

Most of the applications allow users to open or display an empty document. This indicates that such an application expects the user to create a document. Once a document has been created, a user would usually want to store its contents on a medium (hard drive, floppy disk, etc). Microsoft Windows provides a common dialog box for this purpose: The Save As dialog box:

  
The Save As Dialog Box

The primary role of the Save As dialog box is to allow users to store a file on the hard drive of the computer, on a portable medium such as a floppy disk, or on a network drive. To make this efficient and complete, the user must supply two valuable pieces of information: the location and the name of the file. The location of a file is also known as its path.

The name of a file follows the directives of the operating system. On MS DOS and Windows 3.X, it had to be in an 8.3 format. The actual name had to have a maximum of 8 characters with restrictions on the characters that could be used. The user also had to specify three characters after a period. The three characters, known as the file extension, were used by the operating system to classify the file. That was all necessary for those 8-bit and 16-bit operating systems.

Various rules have changed. For example, the names of folders and files on Microsoft Windows >= 95 can have up to 255 characters. The extension of the file is mostly left to the judgment of the programmer but most files are still using extensions. Applications can also be configured to save different types of files; that is, files with different extensions.

To use the Save As dialog box, users usually click an item under the File menu. Here is how it works for most regular applications. The user creates a new document. If the user wants to save the file, he or she can click File -> Save. If the document was not previously saved, the application would call the Save As dialog box. If a document is displaying, whether it was saved previously or not, the user can also click File -> Save As... which also would call the Save As dialog box.

Two objects are particularly important on the Save As dialog box: The Save In combo box and the File Name text box or combo box (the File Name box is made of a combo box to make it user-friendly but over all, users hardly use the list side of this combo box). Since Windows 95, the user does not have to specify an extension if the programmer makes it easy. To help with this, the Save As dialog box is equipped with a Save As Type combo box. This combo box allows the user to select one of the extensions. The available extensions have to be created by the programmer so the user can select from a preset list. If the programmer neglects this, the user would have no extension to select from. Although the file can still be saved, the operating system would not associate it with a known type of file. Therefore, if you specify a series of extensions, the user can select one of these and, in the File Name box, he or she can simply type a name for the file.

If the user does not specify an extension, the operating system would associate the extension of the Save As Type combo box. Users of regular commercial applications, such as word processors, spreadsheet programs, or graphical applications, etc, are usually trained not to care about the extensions and let the application deal with that detail. In some other circumstances, the users must pay close attention to the extension they give a file. This is common on web development or graphics design because various file extensions are supported and overall produce the same end result.

After working on a Save As dialog box, users can click Save or press Enter, which would validate their entry. To change their mind, regardless of what they did on the Save As dialog box, users can click Cancel or press Esc, which would dismiss the dialog box and ignore what they did (in reality, some actions cannot be ignored, such as creating a new file or folder inside of the Save As dialog box, deleting, cutting, or pasting files, etc; but if the user clicked Cancel or pressed Esc, the new file would not be saved).

ApplicationApplication: 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

Creating a Save As Dialog Box

To make a Save As dialog box available to your application, on the Toolbox, you can click the SaveFileDialog button SaveFileDialog Control and click the form. To programmatically provide this dialog box, you can declare a SaveFileDialog variable and initialize it using the class's default constructor as follows:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        sfd = new SaveFileDialog();
    }

    public static int Main()
    {
        [STAThread]
        Application.Run(new Exercise());

        return 0;
    }
}

The SaveFileDialog class inherits from the FileDialog class from which it gets most of its characteristics and behaviors.

ApplicationApplication: Introducing the Save Dialog Box

  1. In the Toolbox, click Dialogs
  2. Click SaveFileDialog SaveFileDialog and click the form
  3. In the Properties window, click (Name) and type dlgSaveFile

Characteristics of the Save As Dialog Box

 

The Title of the Dialog Box

By default, when the Save As dialog box comes up, it displays "Save As" on its title bar. If you want a different caption, set the desired string in the Title field of the Properties window or assign a string to the FileSaveDialog.Title property.

ApplicationApplication: Setting the Title of the Dialog Box

  • Under the form, make sure dlgSaveFile is selected.
    In the Properties window, click Title and type Save an Ice Cream Order

The File Extension

To make sure that your application can open the allowed types of files, depending on your goals, you should create a list of extensions that you want the users to be able to open. The allowed extensions form a group called a filter. The filter is like a funnel that selects the good items. For a text-based application, you may allow only text files, that is, files with a txt extension. For a rich text-based application, you may allow only Rich Text Format files, which are files with rtf extension. On the other hand, if you are creating an application for web files, you can allow as many file extensions as necessary, such as htm, html, php, asp, etc. As you may realize, text files or web files are all text-based files. This means that if you create a text-based or rich-text based application, you should allow the users to decide whether the file they are trying to open can be "read" by a text-based control. To provide this ability, you can specify an unknown extension specified as All Files.

The Filter

To create a list of allowable extensions for your FileSaveDialog object, you can use the Filter property from the Properties window. At run time, you can create a list of file extensions as a string. If the Save As dialog box will need only one extension, you can create the string using the following syntax:

Prompt|Extension

The Prompt is a section that defines what the user would see in the Save As Type combo box. An example would be 24-bit Bitmap. Such a string does not let the user know what actual extension the file would use. Therefore, as a courtesy, you can specify, between parentheses, the extension that would be applied if this extension is used. The Prompt can be 24-bit Bitmap (*.bmp). In this case, the extension used would be bmp. The asterisk * lets the user know that whatever is provided as the file name would be used in place of the asterisk. The period indicates the separation from the file to its extension. This means that the characters on the left of the period would be the file name, the characters on the right side of the period would be used as the actual file extension.

To specify the extension that the operating system would use to associate to the file, you provide a second part of the string as Extension. In Microsoft Windows, most extensions are made of three characters. Some applications use a 2-letter extensions (for example Perl files have a pl extension) and some others use 4 letters (such as html for some HTML files). This depends on the programmer (or the company that is publishing the application). An example of a string as an extension is:

24-bit Bitmap (*.bmp)|*.bmp

If you want to provide various extensions to your Save As dialog box, you can separate them with a | symbol. An example would be:

HTML Files (*.htm)|*.htm|Active Server Pages (*.asp)|*.asp|Perl Script (*.pl)|*.pl

If you added a FileSaveDialog control to a form, as mentioned earlier, you can type the filter string in the Filter field of the Properties window. If your programmatically creating the dialog box, you can assign the string to the Filter property. Here is an example:

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        sfd = new SaveFileDialog();
	sfd.Filter = "HTML Files (*.htm)|*.htm|" +
                                  "Active Server Pages (*.asp)|*.asp|" +
                                  "Apache Files (*.php)|*.php|" +
                                  "Perl Script (*.pl)|*.pl|" +
                                  "All Files|";
    }
}

This would produce:

The Save As dialog box with various file extensions

 

ApplicationApplication: Specifying the Filter

  • Under the form, make sure dlgSaveFile is selected.
    In the Properties window, click Filter and type
    Clarksville Ice Cream File (*.cic)|*.cic| All Files (*.*)|(*.*)

The Filter Index

A filter organizes its extensions and categories as indexes. The above filter has the following indexes:

Index 1 = HTML Files (*.htm)
Index 2 = Active Server Pages (*.asp)
Index 3 = Apache Files (*.php)
Index 4 = Perl Script (*.pl)
Index 5 = All Files;

After creating a filter, when the dialog box comes up, the Save As Type combo box displays the first index of the filter. If you want, instead of displaying the first index by default, you can specify another index. To specify the desired index at design time, change the value of the FilterIndex field in the Properties window. To programmatically specify it, assign a value to the FileSaveDialog.FilterIndex property. Here is an example:

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
       	sfd = new SaveFileDialog();
	sfd.Filter = "HTML Files (*.htm)|*.htm|" +
                                  "Active Server Pages (*.asp)|*.asp|" +
                                  "Apache Files (*.php)|*.php|" +
                                  "Perl Script (*.pl)|*.pl|" +
                                  "All Files|";
    	sfd.FilterIndex = 3;
    }
}

Once you know the types of files that your application will be dealing with, you can make your dialog box friendly by displaying the most likely extension for a document created using your application. For example, if you create a text-based application, users are more likely to create a text file with it. If you create a rich text-based application, users are more likely to create a Rich Text Format file with it. This most likely extension is known as the default extension, it allows the user not to provide an extension in the most likely cases when saving a file. By simply providing a file name and clicking Save, the operating system would associate the file with the default extension. Of course, if you create a filter, the user can specify a desired allowed extension.

The Default Extension

To specify the default extension for your FileSaveDialog object, type the desired extension in the DefaultExt field of the Properties window. If you had created a Filter and if you provide a default extension for a FileSaveDialog object, make sure it is one of the file extensions specified in the Filter list. To programmatically specify a default extension, assign it to the DefaultExt property of your FileSaveDialog variable. Here is an example:

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        	sfd = new SaveFileDialog();
	sfd.Filter = "HTML Files (*.htm)|*.htm|" +
                                  "Active Server Pages (*.asp)|*.asp|" +
                                  "Apache Files (*.php)|*.php|" +
                                  "Perl Script (*.pl)|*.pl|" +
                                  "All Files|";
    	sfd.FilterIndex = 3;
    	sfd.DefaultExt = "htm";
    }
}

ApplicationApplication: Specifying the Default Extension

  • Under the form, make sure dlgSaveFile is selected.
    In the Properties window, click DefaultExt and type cic

Displaying the Dialog Box

Once the OpenFileDialog object is ready, to display it to the user, call its ShowDialog() method. Here is an example:

using System;
using System.Windows.Forms;

public class Exercise : Form
{
    private SaveFileDialog sfd;

    public Exercise()
    {
	InitializeComponent();
    }

    void InitializeComponent()
    {
        sfd = new SaveFileDialog();
        sfd.Filter = "HTML Files (*.htm)|*.htm|" +
                                  "Active Server Pages (*.asp)|*.asp|" +
                                  "Apache Files (*.php)|*.php|" +
                                  "Perl Script (*.pl)|*.pl|" +
                                  "All Files|";
        sfd.FilterIndex = 3;
        sfd.DefaultExt = "htm";

        sfd.ShowDialog();
    }
}

public class Program
{
    public static int Main()
    {
        Application.Run(new Exercise());

        return 0;
    }
}

Microsoft Windows operating systems, especially since Windows 9X, are configured to have a default folder in which users are most likely to save their files. On Windows 9X, it is C:\My Documents. On Windows NT, it is usually specified by the network administrator. On Windows 2000 and Windows XP, it uses a more customized scenario. These settings are known to the operating system and you will usually not be concerned with them. In some circumstances, if you want to specify the folder in which the users should save their files by default, you can provide it using the InitialDirectory property. This directory usually ends with \My Documents. If you want to find the path to the My Documents for a user, you can call the Environment.GetFolderPath() method and pass it the Personal member of the Environment.SpecialFolder enumerator. The syntax of the GetFolderPath() method is:

public static string GetFolderPath(SpecialFolder folder);

Here is an example:

private System.Void button1_Click(System.Object    sender, System.EventArgs    e)
{
    string strMyDocuments = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    this.textBox1.Text = strMyDocuments;
}

Once again, most of the time, you will not be concerned with this issue if you are creating an application for any user.

Probably the most important issue users care about, as far as they are concerned, is a name for the file they are trying to save. Users know that they can set the name of the file in the File Name box. To make this action a little faster, you can provide a default name for a file in case a user does not want to specify a file name. This is done by typing a name in the FileName field of the Properties window. In practicality, the FileName value is the string that displays in the File Name box of the Save As dialog box.

 
 

Home Copyright © 2010-2014, FunctionX