10
votes

C# / .NET 3.5 / WinForms

I've got a form that opens a modal dialog form which opens another modal dialog form. The inner dialog form has OK and Cancel buttons and its AcceptButton and CancelButton are set to them respectively.

When I hit Enter or click OK in the inner dialog, the outer dialog closes as well. I can't see where I'm doing this - is this expected behaviour?

I can supply code but I didn't want to clutter this up.

2
Is the outer dialog running modally [via .ShowDialog] ? You should be able to place a breakpoint after the call in a debugger. But I guess you wouldnt have asked if there wasnt some subtlety to what you're doing... - Ruben Bartelink
Yeah, I'd stepped through the code but it just popped from the inner to the outer without hitting anything. - serialhobbyist

2 Answers

19
votes

This happens because a ShowDialog call modifies its owner's state as well.

To prevent this from happening, you need to reset the DialogResult of the first modal dialog to DialogResult.None after the ShowDialog call to the second dialog:

private void Button1_Click(object sender, EventArgs e)
{
    InnerDialog inner = new InnerDialog()
    DialogResult innerResult = inner.ShowDialog(this);
    this.DialogResult = DialogResult.None;
}

This has been a long-standing issue (see this post).

0
votes

I have struggled with this the whole day until I found this post. It has not been fixed in .NET 4.