Reputation: 1
How would I change the displayed text in a combobox that is a dropdownstyle after something is selected in vb.net? For example, if the user picks "dog" from the list, it will display a number 1 instead of dog.
Upvotes: 0
Views: 115
Reputation: 15774
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
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
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.
Upvotes: 2