When a form is shown using the ShowDialog
method, it is necessary to set the form's DialogResult
property to close to form. This property can be set using the enum that's also called DialogResult.
To close a form, you just need to set the form's DialogResult
property (to any value by DialogResult.None
) in some event handler. When your code exits from the event handler the WinForm engine will hide the form and the code that follows the initial ShowDialog
method call will continue execution.
private cmdClose_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
The calling code can capture the return value from ShowDialog to determine what button the user clicked in the form. When displayed using ShowDialog()
, the form is not disposed of automatically (since it was simply hidden and not closed), so it is important to use an using
block to ensure the form is disposed.
Below is an example of checking the result of using the built-in OpenFileDialog
, checking the result, and accessing a property from the dialog before disposing it.
using (var form = new OpenFileDialog())
{
DialogResult result = form.ShowDialog();
if (result == DialogResult.OK)
{
MessageBox.Show("Selected file is: " + form.FileName);
}
}
You can also set the DialogResult
property on a button. Clicking that button will set the DialogResult
property on the form to the value associated with the button. This allows you close the form without adding an event handler to set the DialogResult
in the code.
For example, if you add an OK button to your form and sets its property to DialogResult.OK
then the form closes automatically when you press that button and the calling code receives a DialogResult.OK
in return from the ShowDialog()
method call.