I would like to know if my current way of opening and closing DB connection is correct.

In the execQuery function i added the DB connection after it executes. I call this function in the web form executeButton so i assume it closes.

In the case the try and catch exeption is triggered in the executeButton does it skip over the DB close?
Or does the DB connection closes first and then the try and catch exception is triggered?

**SQL Control**

```
Public Function ExecQuery(query As String) As DataTable

    Dim DBDT = New DataTable
    Using DBCon As New SqlConnection(ConStr),
            DBCmd As New SqlCommand(query, DBCon)
        Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
        Params.Clear()
        DBCon.Open()
        DBDT.Load(DBCmd.ExecuteReader)
        DBCon.Close()
        If DBCon.State = ConnectionState.Open Then DBCon.Close()
    End Using
    Return DBDT
End Function

```

**Web Form code**

```
Protected Sub ExecuteButton_Click(sender As Object, e As EventArgs) Handles ExecuteButton.Click
    Dim StoreID As Integer
    Dim TransID As Integer
    Dim RgstID As Integer
    Dim dt As DataTable

    If Not Integer.TryParse(StoreIDTextbox.Text, StoreID) Then
            MsgBox("Invalid input. Please enter both Store ID and Transaction ID.")
        Exit Sub

    End If

    If Not Integer.TryParse(TransactionIDTextbox.Text, TransID) Then
        MsgBox("Invalid input. Please enter both Store ID and Transaction ID.")
        Exit Sub
    End If

    SQL.AddParam("@Str_ID", StoreID)
    SQL.AddParam("@Tran_ID", TransID)

    'Rgst_ID Validation
    If RegisterIDTextbox.Text.Length = 0 Then
        SQL.AddParam("@Rgst_ID", "")
    ElseIf RegisterIDTextbox.Text.Length > 0 Then
        RgstID = Integer.Parse(RegisterIDTextbox.Text)
        SQL.AddParam("@Rgst_ID", RgstID)
    End If

    Try
        dt = SQL.ExecQuery("Select H.Emp_ID, H.Cust_ID, H.Rgst_ID, D.TRAN_LN_NUM, D.DISC_CD, D.AUTH_EMP_ID, D.ORIG_PRC, D.DISC_AMT, D.DISC_PCT, D.GL_ACCT_ID
                             From Transaction_Header H 
                             INNER Join LN_Detail L On (H.Str_ID = L.Str_ID And H.Rgst_ID = L.Rgst_ID And H.Tran_ID = L.Tran_ID)
                             INNER Join LN_Discount D ON (L.Str_ID = D.Str_ID And L.Rgst_ID = D.Rgst_ID And L.Tran_ID = D.Tran_ID And L.Tran_LN_Num = D.Tran_LN_Num)  
                             WHERE(H.Str_ID = @Str_ID)
                                And (H.Tran_ID = @Tran_ID)
                                And ((H.Rgst_ID = @Rgst_ID) Or (@Rgst_ID Is NULL Or @Rgst_ID = ''))")

        GridView1.DataSource = dt
        GridView1.DataBind()

    Catch ex As Exception

        MsgBox(ex.Message)
        Exit Sub

    End Try

```