Why does closing a dialog box of a nested child also close the parent dialog?

I open the form as a modal dialog using ShowDialog. This dialog, in turn, allows you to reopen another form in the form of a modal dialog using ShowDialog.

When the internal dialog is closed, this forces the parent dialog to close. Why is this happening and how can I prevent it?

I have illustrated this world version of the problem.

Form 1:

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:

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:

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 play:

  • 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).

+5
1

EDIT:

(: Form2.Designer.cs):

this.OpenForm3Button.DialogResult = System.Windows.Forms.DialogResult.Cancel;

OpenForm3Button, OpenForm3Button_Click, form.DialogResult Cancel .

Reset DialogResult OpenForm3Button :)

+14

All Articles