MGBrown.com

How to use a ComboBox bound to a DataSet in VB.Net

Assume you want to view one field of a DataSet in a ComboBox or ListView, and in code get a different associated field.

First you need a populated dataset then all you need to do is set the DisplayMember, ValueMember and DataSource properties.

Note: You should set the valuemember before setting the datasouce. This is because the SelectedValueChanged event fires for each row in the dataset that you are adding and if the ValueMember is not set you could get a type mismatch.

To see an example simply add a ComboBox to a Windows form and stick this in the code behind file:

Private Sub Form1_Load(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles MyBase.Load
   Dim ds As DataSet = New DataSet
   ds.Tables.Add("Test")

   ds.Tables("Test").Columns.Add("Display", GetType(String))
   ds.Tables("Test").Columns.Add("Value", GetType(String))

   For i As Int16 = 10000 To 10010
      Dim dr As DataRow = ds.Tables("Test").NewRow()
      dr("Display") = i.ToString("C")
      dr("Value") = i.ToString("G")
      ds.Tables("Test").Rows.Add(dr)
   Next

   ComboBox1.DisplayMember = "Display"
   ComboBox1.ValueMember = "Value"
   ComboBox1.DataSource = ds.Tables("Test")
End Sub


Private Sub ComboBox1_SelectedValueChanged(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles _
      ComboBox1.SelectedValueChanged

   If ComboBox1.SelectedIndex <> -1 Then
      Dim ItemSelected As String
      ItemSelected = ComboBox1.SelectedValue
      MsgBox("Value Selected = " & _
         ItemSelected, MsgBoxStyle.Information)
   End If
End Sub

Comments

Sorry, this post is no longer accepting comments.