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:
Form 3 closes with DialogResult == Cancel as expected, but Form 2 also closes with DialogResult == Cancel (not expected).
EDIT :
the problem is this one (file: Form2.Designer.cs
):
this.OpenForm3Button.DialogResult = System.Windows.Forms.DialogResult.Cancel;
when you click the OpenForm3Button
, after the end of the OpenForm3Button_Click
event handler, the form.DialogResult
is automatically set to Cancel
and it is closed.
Reset the DialogResult
property of OpenForm3Button
and it will work as expected :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With