I need some help with correctly implementing the USING statement with strongly typed TableAdapters
I have something like this:
Using myDT As New mbr_Account.mbr_AccountDataTable
Using myTA As New mbr_AccountTableAdapters.mbr_AccountTableAdapter
myTA.Connection.Open()
myTA.Fill(myDT)
myTA.Connection.Close()
End Using
For Each row In myDT
'do stuff
Next
End Using
This would correctly dispose of the datatable and tableadapter but does not address the issue of the connection object.
How should I dispose the Connection object?
I could wrap the connection in a Try… Finally like this:
Using myDT As New mbr_Account.mbr_AccountDataTable
Using myTA As New mbr_AccountTableAdapters.mbr_AccountTableAdapter
Try
myTA.Connection.Open()
myTA.Fill(myDT)
Finally
If Not IsNothing(myTA.Connection) Then
myTA.Connection.Close()
myTA.Connection.Dispose()
End If
End Try
End Using
For Each row In myDT
'do stuff
Next
End Using
Question : How can I use the USING keyword instead of Try.. Finally for the connection object?
I have just found out that TableAdapters handle opening and closing of connections automatically and there is no need to manually add the code.
Basically, they already contain Try … Finally blocks to handle closing of connections during exceptions.
The Designer generated Insert/Delete/Update code looks like this:
Therefore no need to close or dispose the connection object.