I open a form as a modal dialog using ShowDialog. This dialog in turn allows another form to be opened as a modal dialog again using ShowDialog.
When the innermost dialog is closed, this causes its parent dialog to close as well. Why does this occur and how can I prevent it?
I have created a hello world version of the problem to illustrate this.
Form 1:
private void OpenForm2Button_Click(object sender, EventArgs e)
{
Form2 testForm = new Form2();
DialogResult dialogResult = new DialogResult();
dialogResult = testForm.ShowDialog();
MessageBox.Show("Form 2 returned: " + Convert.ToString(dialogResult));
}
Form 2:
...
this.Form2OKButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Form2CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
...
this.AcceptButton = this.Form2OKButton;
this.CancelButton = this.Form2CancelButton;
...
private void OpenForm3Button_Click(object sender, EventArgs e)
{
Form3 testForm = new Form3();
DialogResult dialogResult = new DialogResult();
dialogResult = testForm.ShowDialog();
MessageBox.Show("Form 3 returned: " + Convert.ToString(dialogResult));
}
Form 3:
...
this.Form3OKButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.Form3CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
...
this.AcceptButton = this.Form3OKButton;
this.CancelButton = this.Form3CancelButton;
Steps to reproduce:
- Click "Open Form 2"
- Click "Open Form 3"
- Click "Cancel"
Form 3 closes with DialogResult == Cancel as expected, but Form 2 also closes with DialogResult == Cancel (not expected).
Best Answer
EDIT :
the problem is this one (file:
Form2.Designer.cs
):when you click the
OpenForm3Button
, after the end of theOpenForm3Button_Click
event handler, theform.DialogResult
is automatically set toCancel
and it is closed.Reset the
DialogResult
property ofOpenForm3Button
and it will work as expected :)