How to Fill and Get the Value Member of a ListBox in Visual Basic 2008 and MS Access Database

This time, I’m going to teach you how to fill and get the value member of a ListBox by using Visual Basic 2008 and MS Access Database. With this tutorial, you can fill the data to the ListBox that came from the Database and get its Id by clicking the name that shows in the ListBox. Let’s begin: Open the Visual Basic 2008 and create a new Windows Form Application. Drag a button and a ListBox in the Form. Do the Form just like this. FillingData Go to the Solution Explorer and click the View Code. FillingDataCodeView In the View Code, declare all the classes and the variables that are needed.
  1.   'Setting up the connection string
  2.     Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
  3.                                                                 & Application.StartupPath & "/member.accdb")
  4.     'Represents as a set of data command and the
  5.     'database connection the are used to fill and update the datasource
  6.     Dim da As New OleDb.OleDbDataAdapter
  7.     'Represents one table of the database
  8.     Dim dt As New DataTable
  9.     'A variable that holds the query
  10.     Dim query As String = "SELECT * FROM tblmember"
Go back to the Design Views, double click the button and do this following code for filling the data in the ListBox.
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.         'opening the connection
  3.         con.Open()
  4.         'Holds the data to be filled.
  5.         da = New OleDb.OleDbDataAdapter(query, con)
  6.         'Set a new table
  7.         dt = New DataTable
  8.         'Fill the data in the datatable
  9.         da.Fill(dt)
  10.  
  11.         With ListBox1
  12.             'Set the datasource of a Listbox
  13.             .DataSource = dt
  14.             'Set the Field to be displayed
  15.             .DisplayMember = "membername"
  16.             'Set the actual value of the items
  17.             .ValueMember = "ID"
  18.         End With
  19.         con.Close()
  20.     End Sub
After that, go back to the Design Views click the ListBox and go to the properties. Hit the Events and double-click the “Click” for the Events handler of a ListBox. FillingDataProperties Do this following code for in the Click Event Handler of a ListBox.
  1.  
  2. Private Sub ListBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.Click
  3.         'The actual value of the items will be appear in the
  4.         'messagebox everytime you click the listbox
  5.         MsgBox("The ID is : " & ListBox1.SelectedValue)
  6.     End Sub
Download the complete source code and run it on your computer.

Comments

Easy to Understand and d=Detailed thank you very much

Add new comment