More on Databases June 30, 2008
Posted by tuse in : Databases, Tips and Tricks, VB.NET , add a commentIn the previous post, we were introduced to the usage of MySQL Databases in VB.NET.
Today we focus on binding data from databases into controls.
What we will try to do is populate a ListBox Control with data from a table.
So in a new form, drag a ListBox Control from the ToolBox.
We will use a Data Reader (there are other methods too which will be explained soon) to bind the data to the ListBox. The Data Reader reads data from the table specified as directed by the Connection String and the SQL Command.
A simple while loop is set up to add the available data to a ListBox as long as we are through reading all the records. The population of the ListBox is done in the ‘Form_Load’ event.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New Odbc.OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=mydb; User=root;Password=;")
Dim cmd As New Odbc.OdbcCommand("Select * from mytable", cn)
cn.Open()
' Use a Data Reader Object to read Records from the table
Dim dr As Odbc.OdbcDataReader
dr = cmd.ExecuteReader
While dr.Read 'While there are records
Me.ListBox1.Items.Add(dr.Item(1))
' Add the 2nd Field of the table into the ListBox. To add the n th field, give dr.Item(n-1)
End While
cn.Close()
End Sub
End Class
