.Net HowTo - Connection Events
Weirdly enough, in the new .Net it’s OK to close a closed connection (can’t close anything you haven’t opened?!), but it raises an error if you try to open an open connection! In my opinion you shouldn’t rely on being able to close a closed connection in your programming,
Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOpen.Click Try If (objConn.State <> ConnectionState.Open) Then objConn.Open() End If Catch objError As Exception MessageBox.Show(objError.Message) End Try End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click Try If (objConn.State <> ConnectionState.Closed) Then objConn.Close() End If Catch objError As Exception MessageBox.Show(objError.Message) End Try End Sub
Here objConn is a SQLConnection object from the toolbar dragged onto a webform. The two functions are fired by two buttons on the windows from denoting an open event and a close event.