How to: Close Dialog Boxes and Retain User Input

You can set the way a dialog box is closed at either design time or run time. At design time, you can set the DialogResult property for all of the Button controls on a dialog box. At run time, you can set the DialogResult property so you can dynamically handle user responses.

Note Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Customizing Development Settings.

To set the DialogResult property for a control at design time

  1. Click on the Button control that you want to set the property for.

  2. In the Properties window, select the DialogResult property and open the list of available property settings.

  3. Select the appropriate dialog box result.

    You can set the dialog box result for user-performed actions other than clicking a Button control. If your dialog box does not contain buttons to close the dialog box, you can set the result of the dialog box at run time.

To set the DialogResult property for a control or form programmatically

  1. Navigate to the event handler or method that you want to set the DialogResult property for.

  2. Author code similar to the following code example.

    private void InformationProcessed() 
    {
       // This code will set the DialogResult for a form.
       DialogResult = DialogResult.Yes;
       // OR
       // This code will set the DialogResult for a button.
       button1.DialogResult = DialogResult.No;
    }
    

    Although setting the DialogResult property will cause your dialog box to close automatically, you can still handle the control's Click event, and the dialog box will close once the event handler's code is finished. While handling the Click event, you may want to halt the closure of the dialog box.

To stop the DialogResult property from closing the dialog box

  • In the event handler, author code similar to the following code example.

    private void button1_Click(object sender, System.EventArgs e) 
    {
       DialogResult = DialogResult.None;
    }
    
    NoteNote

    You can also use the Closing event of the form to stop the closing of a dialog box.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft