views:

41

answers:

2

I want to run a subroutine to clear some things up when the user exits the application. I tried looking for a Form_Unload event or anything similar, is there a way to do this?

I open a database connection on Form_Load, and would like to close it when the user exits the app.

Thanks.

+2  A: 

Most of the time, you should try not to hang on a connection for the lifetime of an application. You should open and close it as needed. If you don't want to close and reopen it as a performance optimization, you don't need to worry about it. Connection pooling for the database driver should handle that.

Anyway, you don't really need to close the connection if the process is going to end. The acquired resources will get released automatically.

If you want to execute code as the form gets closed, you can handle its FormClosing event. If you want the code to execute after a form is closed, handle its FormClosed event.

Mehrdad Afshari
@Mehrdad: Closing and Closed are obsolete, FormClosing and FormClosed are their replacements.
Hans Passant
@nobugz: really? +1. I have moved to WPF long ago. Haven't seen the new stuff in WinForms in detail. Thanks for pointing out.
Mehrdad Afshari
Odd how you ended up with the +1. SO mystifies me sometimes.
Hans Passant
@nobugz: I expect it to be for the first part of my answer: don't leave the connection open, close it when you're done with it.
Mehrdad Afshari
@Mehrdad - so +1 doesn't actually mean "one upvote", it is more like "a-one dude!"? Trying to de-mystify SO for myself, sorry for the noise.
Hans Passant
@nobugz: Oops. Got it dude. I had upvoted your comment then edited my answer. Didn't notice the other answer is yours. Sorry.
Mehrdad Afshari
@Mehrdad - sounds credible. Erm, what other answer? Please don't address me as "dude", nobody that likes their current pair of glasses ever does.
Hans Passant
@nobugz: You seem pretty angry. Sorry if you got offended for anything I caused. It's 2AM here and I'm not sure what I'm doing.
Mehrdad Afshari
@Mehrdad - got the message across, carry on.
Hans Passant
+2  A: 

Use the FormClosing event. The MSDN Library article is here. Poke around a bit more, these are the kind of events you need to know pat to do any kind of Windows Forms programming.

Hans Passant