Web Design that taps into the haromny and vision of your dreams.

Using Common Dialogue Boxes in C#

Using the OS standard dialogue boxes

Written By on in C#

1,243 words, estimated reading time 6 minutes.

Visual Studio and Visual C# provide dialogue boxes for common tasks such as Open, Save and Print. In this tutorial, we will have a look at some of the dialogue boxes and see how we can load and save data in our program.

Windows Forms Applications Series
  1. Basics of C# Windows Forms Applications
  2. Menus, Popups and Toolbars in .Net Forms and C#
  3. Using Common Dialogue Boxes in C#
  4. List Boxes and Tree Views in C#
  5. List Box Data Binding in C# Windows Forms Application
  6. Using Multiple Forms in C# Applications with MDI
  7. Creating Controls for Windows Forms and C#
  8. Saving User Preferences and Settings within your C# Application

This tutorial continues on from our last tutorial where we created a notepad text editor application. You will need the source code from the last tutorial, if you don't have it you can download it here.

The common controls are listed under the Dialogues tab of the toolbox. You will have to drag these onto the grey area beneath the form editor, as they are non-visual components.

We are going to create menus and buttons for Open, Save and Save As. We will also need to add some simple logic to our program to detect modifications to the text. We will also look at the form closing events.

Add menu items for Open, Save and Save As to the menu strip we created in the last tutorial. You may wish to separate items with a horizontal line in order to group items of similar function. You can do this by just entering a - (minus symbol) to the text of an item, it will then change to a breaker bar. Don't forget to name each item appropriately.

There is a standard convention that should be observed regarding menu items which open a dialogue or another form, they should always end with an ellipses (three dots) to indicate another window will appear. For example "Save As...".

You should also set keyboard shortcuts to common tasks (such as Ctrl+C for Copy) and hotkeys for each time (Alt+Letter). Hotkeys are assigned by adding an ampersand before the letter, so "Save As" would become "Save &As". This will appear on the menu as "Save As".

My menu now looks like the image on the right, you can see the how separators group the menu items, and the shortcut and hot keys.

While we are adding menu items you can also create a Format menu after the File menu with sub menus for Bold, Italic and Underline and assign the events we created in the last tutorial. If you wish, you can assign icons to the menu items in exactly the same way as we add images to the toolbar buttons in the last tutorial.

Notepad Lite File Menu
Notepad Lite File Menu

Back to the topic of today's tutorial, the common dialogue boxes. Double click on the open menu item to wire up the event and open the code editor. Key in the following code, which will display the dialogue box and load the contents of the file selected.

private void evtOpenFile_Click(object sender, EventArgs e)
{
  if (openFileDialog1.ShowDialog() == DialogResult.OK)
  {
    richTextBox1.LoadFile(openFileDialog1.FileName,
      RichTextBoxStreamType.PlainText);
    saveFileDialog1.FileName = openFileDialog1.FileName;
  }
}

The ShowDialog method returns a DialogResult type based on which button was clicked by the user. In this case we are only interested in performing an action if the user selected a file and pressed OK. The openFileDialog will store the selected filename within the FileName property, which can be passed into the richTextBox LoadFile method. We also need to specify the type of file using a RichTextBoxStreamType type of PlainText. The final line assigns the value of openFileDialog1.FileName to the equivalent property of the saveFileDialog in order for us to simply save the file without prompting for a filename.

When you run the program and open a file, you will notice that we now have a standard Windows open dialog box that you should be familiar with. You may also notice that we can open any file, including text files, images or even executables. Ideally we need to be able to limit the types of file that the user can open and we can do that by adding a filter to the OpenDialogBox properties.

Back in the form designer, click on the OpenDialog component and open the properties window and find the Filter property. We need to add in a few file types that we want the user to be able to open. Surprisingly, Visual Studio does not give us a nice property editor for this, so we have to do it by hand. The format for the filter string is Description|Ext|Description|Ext and so on. For our program we want to be able to open Text Files (*.txt) and Rich Text Files (*.rtf) so our filter string will be

All Supported Files (*.txt; *.rtf)|*.txt;*.rtf|Text Files (*.txt)|*.txt|Rich Text Files (*.rtf)|*.rtf

Now when you run the program you will see that the user can only see files of type Text File or Rich Text File or Both.

Next, we will wire up the Save As menu item in a similar method. Double click on the menu item to create the event handler method. We can copy and paste some of the code from the open method, changing a few of the variable names around. Don't forget to change the Filter property the same as our open dialog, except we should remove the All Supported Files item.

private void evtSaveAs_Click(object sender, EventArgs e)
{
  if (saveFileDialog1.ShowDialog() == DialogResult.OK)
  {
    richTextBox1.SaveFile(saveFileDialog1.FileName,
      RichTextBoxStreamType.PlainText);
  }
}

You can test this and it will save the current file to disk. The .Net platform will automatically check if a file exists and ask the user to confirm overwriting of the file. You can change this behaviour by altering the OverwritePrompt property of the Save dialogue.

Our final event is the Save method. This is an easy method, but relies on our Save As method.

private void evtSave_Click(object sender, EventArgs e)
{
  if (saveFileDialog1.FileName != "")
  {
    richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
  }
  else
  { 
    evtSaveAs_Click(sender, e);
  }
}
 

First we check if the FileName is empty. If we have a filename then just call the SaveFile method. If it is empty (i.e. a new document) we need to find out from the user what filename to save the data to so we just call the Save As action which he have already written to get a filename from the user.

There is one final method we need and that is to ask the user if they want to save changes on exit. C# provides an event on the form called FormClosing which is called when the form starts to close. From within this method you can tell the form not to close, or perform some actions that must be executed at the end of the program (i.e. closing connections or files).

We can use this function to see if the RichTextBox needs to be saved and prompt the user.

private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
{
  if (richTextBox1.Modified) 
  {
    DialogResult result = MessageBox.Show("Do you wish to Save changes?", "Save Changes", MessageBoxButtons.YesNoCancel);
 
    if (result == DialogResult.Yes)
      evtSave_Click(sender, e);
    else 
      if (result == DialogResult.Cancel) 
        e.Cancel = true;
  }
}

And there we have it, our Notepad Lite application is coming along nicely, and we have learned how to use the save and open common dialogue boxes as well as saving and loading text files.

Now you have reached the end of this tutorial, why not try and add an edit menu with the items Cut, Copy and Paste. You can also add these buttons to the toolbar and the context menu.

Hint: You need to look for the Cut, Copy and Paste methods in the RichTextBox control, and you will also need to check if you CanPaste and disable the control if you can't. It will need to be checked on the Form Load as well as when you Copy or Cut.

Last updated on: Friday 23rd June 2017

 

Comments
Divyesh Vaghela

Divyesh Vaghela

I am a begginer in C# windows forms application development. I have learned about most of the important controls and components and I learn the actual implementation of the common dialogue controls from this page. So thank you very much...

Reply to Divyesh Vaghela
CE

CE

Great tutorial -- I looked for hours before a found an excellent example without navigating through the whole site.
I bookmarked your site -- I'll definitely be back !!

Reply to CE
eb-5 visa

eb-5 visa

Good and useful tutorial for beginners.It helps me a lot.

Reply to eb-5 visa
matsolof

matsolof

Good and useful tutorial for beginners.

Reply to matsolof

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me