How to Use Dialogs


As CommonDialog is the base class for the dialog classes, all the dialog classes can be used similarly. Public instance methods are ShowDialog() and Reset(). ShowDialog() invokes the protected RunDialog() instance method to display the dialog and finally returns a DialogResult instance with the information on how the user interacted with the dialog. Reset(), in contrast, sets properties of the dialog class to their default values.

The following code segment shows an example of how a dialog class can be used. Later, you take a more detailed look at each of the steps, but first you get an introduction explaining how dialogs can be used.

In the following code segment you can see how to use a dialog class:

 OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Sample"; dlg.ShowReadOnly = true; if (dlg.ShowDialog() == DialogResult.OK) { string filename = dlg.FileName; } 
  • First a new instance of the dialog class is created.

  • Next, you have to set some properties to enable and disable optional features and set dialog state. In this case, you set the Title property to "Sample", and the ShowReadOnly property to true.

  • By calling the ShowDialog() method, the dialog is displayed, waiting for and reacting to user inputs.

  • If the user presses the OK button, the dialog closes, and you check for the OK by comparing the result of the dialog with DialogResult.OK. After that you can get the values from the user input by querying for the specific property values. In this case, the value of the FileName property is stored in the filename variable.

It's really that easy! Of course, every dialog has its own configurable options, which you look at in the following sections.

If you use a dialog from within a Windows Forms application in Visual Studio, it's even easier than the few lines of code above. The Windows Forms designer creates the code to instantiate a new instance, and the property values can be set from the Properties window. You just have to call ShowDialog() and get to the changed values, as you shall see.




Beginning Visual C# 2005
Beginning Visual C#supAND#174;/sup 2005
ISBN: B000N7ETVG
EAN: N/A
Year: 2005
Pages: 278

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net