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?
When you are changing the
DialogResult
property of aForm
(which is shown withShowDialog()
), 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:
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)