When to close a form in relation to an error.

  • Thread starter Thread starter AMeador
  • Start date Start date
A

AMeador

I have a form that will make a connection to a database. The form
has a form level variable/object defined so all parts of the form can
share the connection. What I want to do is open the connection in the
constructor, or form load event handler, and if there is an error in
the connection, I want to notify the user of the error and close the
form. I put a messagebox, to notify the user of the error, in the catch
block and also 'this.close' in the catch block immediately after the
messagebox. When I put this in the constructor, the error is shown to
me, but the form still loads. When I put it in the form load event
handler, the form closes, but it still runs the code after the catch
block. I question whether this is the even the best way to go about
doing this, so if you have a better idea - let me know. If this is
good, but I'm just missing something, also please let me know. ;)
Thanks!
 
AMeador,

From a design standpoint, I don't think that this is a good idea. You
should open the connection and pass it into your form.

Even this is a bad idea. When dealing with DB connections, you should
get the connection when you need it, perform your work, and close it.

If you still want to open a connection in the form, then you should
re-throw the exception in the constructor. This will prevent the form from
being constructed, but in that case, you will have to deal with a null
exception where it is used (the form).

If you use the form load event, then after you call close on the form,
return from the method, so that the code after the catch is not called.

Hope this helps.
 
Back
Top