Change Text in Vb.net DropDownStyle Combobox after an item is selected

Solution 1:

There are a couple ways to do this. Either way, you must have some relationship between the animal name and id. So here's a basic class

Public Class Animal
    Public Sub New(id As Integer, name As String)
        Me.Name = name
        Me.ID = id
    End Sub
    Public Property ID As Integer
    Public Property Name As String
End Class

keep a list of Animal

Private animals As List(Of Animal)

and populate it

animals = New List(Of Animal)()
animals.Add(New Animal(1, "Dog"))
animals.Add(New Animal(2, "Cat"))
animals.Add(New Animal(3, "Fish"))

Two ways I mentioned

  1. Using this list as a DataSource
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = animals
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1?.SelectedIndex > -1 Then
        Me.BeginInvoke(Sub() ComboBox1.Text = DirectCast(ComboBox1.SelectedValue, Integer).ToString())
    End If
End Sub
  1. Populating the ComboBox with string names

You do still need the class to keep a relationship between animal name and id

ComboBox1.Items.AddRange(animals.Select(Function(a) a.Name).ToArray())
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
    If ComboBox1?.SelectedIndex > -1 Then
        Me.BeginInvoke(Sub() ComboBox1.Text = animals.SingleOrDefault(Function(a) a.Name = ComboBox1.SelectedItem.ToString())?.ID.ToString())
    End If
End Sub

Both methods will produce the same result, but I would say the DataSource is nicer since you can just get the ComboBox1.SelectedValue as an Animal, and retrieve either the Name or ID simply, instead of using some LINQ to extract the ID in the second case.

enter image description here