ComboBox
comes in handy for connecting to a database using ComboBox DataSource
binding. In this way, we can use data sources for getting selection input from user. Before we start the exercise, understand the following terms for ComboBox
binding:
- Data Source: This is used to fill the Items Collection of
ComboBox
with the data source. If we have a database as a data source, then we may use Table binding source as the data source for ComboBox
. - Display Member: This property from the data source is shown in the list as Items Collection of
ComboBox
. - Value Member: This value is returned from the data source when Selected Value property of
ComboBox
is accessed. - Selected Value: Use this if you want to bind the selected value to a property in data source.
Now, follow the steps below:
- Add our Access Test_Database from the previous post to the project. In case you haven’t read the post, get the information here.
- Place a new
ComboBox1
and Label1
to the project Form Design. - Select the option Use Data Bound Items from the
ComboBox
Tasks: - Select
Table1
for the Data Source property. A new binding source Table1BindingSource
will be created and selected itself. - Select
FirstName
as the Display Member and Value Member. Leave SelectedValue
to (none). - Run the application. You can see that
ComboBox
is showing the list of First Names from the data source:
Get Value of Selected Item from ComboBox DataSource
To get the value of selected item from ComboBox
, paste the following code inside ComboBox1_SelectedIndexChanged sub
:
If Not ComboBox1.SelectedValue = Nothing Then
Label1.Text = ComboBox1.SelectedValue.ToString
End If
The complete code looks like this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Table1TableAdapter.Fill(Me.Test_DatabaseDataSet.Table1)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
If Not ComboBox1.SelectedValue = Nothing Then
Label1.Text = ComboBox1.SelectedValue.ToString
End If
End Sub
End Class
Now the Label1
text is updated whenever user changes the selection:
You may want to retrieve the value of Age
instead of first name for the selected item. To do this, we need to modify the Value
Member property. Go to ComboBox
Tasks and select Age
for Value Member.
Run the application. Label1
is updated with the Age
of the selected Name
:
The post ComboBox DataSource binding in Visual Basic appeared first on Bubble Blog.