How do I bind a ComboBox/ListBox to database table records?
Locked
-
Thursday, April 09, 2009 9:03 AM
How do I bind a ComboBox/ListBox to database table records?
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
All Replies
-
Thursday, April 09, 2009 9:06 AM
Here are two approaches.
Take ComboBox and MS Access database for example:
1) Binding ComboBox to database table records via DataTable object.
Imports System.Data.OleDb Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim con As OleDbConnection = New OleDbConnection( _ "Provider=Microsoft.jet.oledb.4.0;data source=C:\USERS.mdb") Dim cmd As OleDbCommand = New _ OleDbCommand("SELECT Username FROM Table1", con) con.Open() Dim myDA As OleDbDataAdapter = New OleDbDataAdapter(cmd) Dim myDataSet As DataSet = New DataSet() myDA.Fill(myDataSet, "MyTable") 'Idea 1 ComboBox1.DataSource = myDataSet.Tables("MyTable").DefaultView ComboBox1.ValueMember = "Username" ComboBox1.DisplayMember = "Username" ' Idea 2 For Each dRow As DataRow In myDataSet.Tables("MyTable").Rows ComboBox1.Items.Add(dRow.Item("Username")) Next con.Close() con = Nothing End Sub End Class2) Binding ComboBox to database table records via DataReader object.
Imports System.Data.OleDb Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim con As OleDbConnection = New OleDbConnection( _ "Provider=Microsoft.jet.oledb.4.0;data source=C:\USERS.mdb") Dim cmd As OleDbCommand = New _ OleDbCommand("SELECT Username FROM Table1", con) con.Open() Dim sdr As OleDbDataReader = cmd.ExecuteReader While sdr.Read() ComboBox1.Items.Add(sdr.Item("Username").ToString) End While con.Close() con = Nothing End Sub End ClassLikewise, the above approaches are applied to ListBox control.
Related thread:
http://social.msdn.microsoft.com/forums/en/vbgeneral/thread/d6b60aa8-0bff-46f8-90f9-a237d4d3024f/
For more FAQ about Visual Basic Express, please see Visual Basic Express FAQ
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.- Marked As Answer by Xiaoyun Li – MSFT Thursday, April 09, 2009 9:25 AM

