So I have code that runs in a Vb.Net project that reads specific cols from a table in a Access Database (2007). It then populates a Datagridview with the results. The Issue is the code is messy, I'm disposing of all the events...etc. Is there a way to optimize it? From what I read, I can use the command "using" but I'm having problems trying to implement it. Any help on cleaning up this code is associated.
Sub Populate_RecordsList_Via_Database()
'Create a connection to the database
Dim strConnection As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=SBS2257_Info.accdb;"
Dim objConnection As New OleDbConnection(strConnection)
'Open the connection with error handling
Try
objConnection.Open()
Catch OleDbExceptionErr As OleDbException
MessageBox.Show(OleDbExceptionErr.Message)
Catch InvalidOperationErr As InvalidOperationException
MessageBox.Show(InvalidOperationErr.Message)
End Try
'Create a command object with the SQL statement needed to select the first and last names
Dim strSQL As String = "SELECT [RecordID], [FName], [LName], [SBAlias1] FROM [Records];"
Dim objCommand As New OleDbCommand(strSQL, objConnection)
'Create a data adapter and data table then fill the data table
Dim objDataAdapter As New OleDbDataAdapter(objCommand)
Dim objDataTable As New DataTable("Info")
objDataAdapter.Fill(objDataTable)
'close connection and release resources
objConnection.Close()
objConnection.Dispose()
objConnection = Nothing
objCommand.Dispose()
objCommand = Nothing
objDataAdapter.Dispose()
objDataAdapter = Nothing
'Populate datagridview
For Each row As DataRow In objDataTable.Rows
Dim n As Integer = DGV_ListView.Rows.Add()
DGV_ListView.Rows.Item(n).Cells(0).Value = row.Item("RecordID")
DGV_ListView.Rows.Item(n).Cells(1).Value = row.Item("FName")
DGV_ListView.Rows.Item(n).Cells(2).Value = row.Item("LName")
DGV_ListView.Rows.Item(n).Cells(3).Value = row.Item("SBAlias1")
Next
'Release resources
objDataTable.Dispose()
objDataTable = Nothing
End Sub