tags:

views:

35

answers:

2

In my load event on a form, I call some method in a try catch block. When an Exception occurs, I show the user a message and after that I want to close the form. It looks like this (code in Load event):

try
{
   Metehod();
}
catch(DatabaseException ex)
{
  MessageBox.show("db error! " + ex.Message);
  this.Close();
}
catch(Exception ex)
{
  MessageBox.Show("Unknown error!" + ex.Message);
  this.Close();
}

But, when this.CLose() is called, it doesn't close the form, no, the code keeps running till the end of the load event!

Why is this? Is this logical behaviour?

+2  A: 

It's by design because Load occurs before a form is displayed for the first time. So Close() has no effect since three events later in the Form life cycle, the form is shown.

To stop the cycle, use devnull solution.

Pierre 303
+2  A: 

Yes, it is logical behaviour. Calling Close() does not return control to the caller. The method will continue execution unless you tell it otherwise. Putting a return after each this.Close() does the trick.

devnull