Using DialogResult Correctly
When you open a modal dialog with ShowDialog, the calling code is blocked until the form called closes or hides. If you want to read some public properties of the called form and want to do things (for example save data to a database or to a file) based on the click on the OK or Cancel button, then you need to know if the user wants to do the action or not. The DialogResult returned by the ShowDialog() method allows you to take the appropriate actions...
So for example
using (Form1 form = new Form1())
{
DialogResult dr = form.ShowDialog();
if(dr == DialogResult.OK)
{
string custName = form.CustomerName;
SaveToFile(custName);
}
}
An important thing to add to this answer is the fact that the DialogResult
property exists both on the Form class and in the Button class. Setting the button's DialogResult property (both via code or designer) to a value different from DialogResult.None
is the key to activate an important behavior for forms. If you click a button with that property set then the Forms Engine transfers the value of the Buttons property to the Forms one and triggers the automatic closure of the form reactivating the caller code. If you have an event handler on the button click then you can run code to validate the form's inputs and force the form to stay open overriding the form's DialogResult property setting it back to DialogResult.None
For example, in the modally showed form you can have:
// Event handler for the OK button set with DialogResult.OK
public void cmdOK_Click(object sender, EventArgs e)
{
// Your code that checks the form data and
// eventually display an error message.
bool isFormDataValid = ValidateFormData();
// If data is not valid force the form to stay open
if(!isFormDataValid)
this.DialogResult = DialogResult.None;
}
Whether you call Close
or set the DialogResult
property is not really the issue. You just need to make sure to call Dispose
. I prefer doing this with a using block:
using (Form1 form = new Form1())
{
form.ShowDialog();
}
I originally thought that you could call ShowDialog
on a Form
that has already had its Close
method called. This is not the case. If you show the form modally with ShowDialog
, it doesn't seem to matter whether it is closed as a result of the Close
method, or setting the DialogResult
property. It would seem that setting the DialogResult
is just a short-cut for closing the Form
.
But whether you call Close
or set the DialogResult
property, the key is to make sure that you call Dispose()
or put your form in a using block.