Use standard dialogs in C#

To use a standard dialog, first place the dialog on a form and set any properties that you want to customize. For example, you may want to set a file dialog's Filter property. You may also want to set CheckFileExists for the OpenFileDialog and OverwritePrompt or CreatePrompt for the SaveFileDialog. (Although the defaults for those properties are sensible.)

You can create the dialogs in code at run time instead of placing them on a form but it's more convenient to use a form.

Using a dialog at run time is a three step process.

  1. Initialize the dialog. Set dialog properties to show the current settings. For example, set a FontDialog's Font property to the current font.
  2. Display the dialog and check the return result. Call the dialog's ShowDialog method and see if it returns OK, indicating that the user clicked OK.
  3. If the user clicked OK, use the dialog's values to do something. For example, make the form use the font selected in a FontDialog.

The example program lets the user select a file for opening, a file for saving, foreground and background colors, and a font. The following code shows how the program handles font selection.

// Select the font.
private void btnFont_Click(object sender, EventArgs e)
{
// Initialize.
fdFont.Font = this.Font;

// Display and check result.
if (fdFont.ShowDialog() == DialogResult.OK)
{
// Take action.
this.Font = fdFont.Font;
}
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.