Form opened with ShowDialog closes after exception

531 Views Asked by At

I have a FormA from which I open FormB like so:

FormB B = new FormB();
FormB.ShowDialog();

In FormB, I have some code in a try catch block and when it throws the exception, FormB is closed.

private void func()
{
  try
  {
     // some code
     DialogResult = DialogResult.Ok;
     throw new Exception("Test exception")
  } 
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

Take look at that two lines of code. When DialogResult assignment is above exception throw, form closes after exception.

Vice versa, the form is not closing. So can someone explain that behavior?

1

There are 1 best solutions below

2
On

When you are changing the DialogResult property of a Form (which is shown with ShowDialog()), it will be closed. When you raise an exception before setting the property, the property won't be changed, so it won't close the form. When a form isn't displayed as a modal dialog box, clicking the Close button (the button with an X in the top-right corner of the form) causes the form to be hidden.


I'll give some more info. Like the documentation says:

The dialog result of a form is the value that is returned from the form when it is displayed as a modal dialog box. If the form is displayed as a dialog box, setting this property with a value from the DialogResult enumeration sets the value of the dialog box result for the form, hides the modal dialog box, and returns control to the calling form. This property is typically set by the DialogResult property of a Button control on the form. When the user clicks the Button control, the value assigned to the DialogResult property of the Button is assigned to the DialogResult property of the form.

Source

So if you set the property before the exception. It will trigger the dialog to close. (it probably sends a WM_CLOSE message to the form, that's why it doesn't close directly)