How to Fill and Get the Value Member of a ListBox in Visual Basic 2008 and MS Access Database
Submitted by janobe on Monday, August 4, 2014 - 21:08.
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.
Go to the Solution Explorer and click the View Code.
In the View Code, declare all the classes and the variables that are needed.
Go back to the Design Views, double click the button and do this following code for filling the data in the ListBox.
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.
Do this following code for in the Click Event Handler of a ListBox.
Download the complete source code and run it on your computer.
- 'Setting up the connection string
- Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" _
- & Application.StartupPath & "/member.accdb")
- 'Represents as a set of data command and the
- 'database connection the are used to fill and update the datasource
- Dim da As New OleDb.OleDbDataAdapter
- 'Represents one table of the database
- Dim dt As New DataTable
- 'A variable that holds the query
- Dim query As String = "SELECT * FROM tblmember"
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
- 'opening the connection
- con.Open()
- 'Holds the data to be filled.
- da = New OleDb.OleDbDataAdapter(query, con)
- 'Set a new table
- dt = New DataTable
- 'Fill the data in the datatable
- da.Fill(dt)
- With ListBox1
- 'Set the datasource of a Listbox
- .DataSource = dt
- 'Set the Field to be displayed
- .DisplayMember = "membername"
- 'Set the actual value of the items
- .ValueMember = "ID"
- End With
- End Sub
- Private Sub ListBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.Click
- 'The actual value of the items will be appear in the
- 'messagebox everytime you click the listbox
- End Sub
Comments
Add new comment
- Add new comment
- 291 views