简体   繁体   中英

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

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.

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.DataSource = animals
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
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.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM