Here's an example of how to populate a list box with data from the Northwind database which comes with MS Access. Coincidentally this was an exercise in Theron Willis' Beginning Visual Basic 2005 Databases (Chapter2, Exercise 1). Thanks to Mr. Willis for this book, it has been a great help to me!
Code:
Imports System.Data
Imports System.Data.OleDb
PublicClass Form1
PrivateSub Form1_Load(ByVal sender AsObject, ByVal e As System.EventArgs) HandlesMe.Load
'Create a connection to the database
Dim strConnection AsString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Program Files\Microsoft Office\Office11\Samples\Northwind.mdb;"
Dim objConnection AsNew 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)
EndTry
'Create a command object with the SQL statement needed to select the first and last names
Dim strSQL AsString = "SELECT FirstName, LastName FROM Employees"
Dim objCommand AsNew OleDbCommand(strSQL, objConnection)
'Create a data adapter and data table then fill the data table
Dim objDataAdapter AsNew OleDbDataAdapter(objCommand)
Dim objDataTable AsNew DataTable("Employees")
objDataAdapter.Fill(objDataTable)
'Create connection and release resources
objConnection.Close()
objConnection.Dispose()
objConnection = Nothing
objCommand.Dispose()
objCommand = Nothing
objDataAdapter.Dispose()
objDataAdapter = Nothing
'Fill names into the listbox
ForEach row As DataRow In objDataTable.Rows
lstNames.Items.Add(row.Item("FirstName") & " " & row.Item("LastName"))
Next
'Release resources
objDataTable.Dispose()
objDataTable = Nothing
EndSub
EndClass
What this example is doing is opening a connection to the Northwind database, selecting the data from the FristName and LastName columns of the Employees table, and filling that data into a data table. I then use a For Each Next loop to iterate through each row in the data table to add the value in the FirstName and LastName column to the listbox.
Cheers!