在vb.net中选择了某些内容之后,如何更改组合框中显示的文本,这是一个下拉样式?例如,如果用户从列表中选择“狗”,它将显示一个数字1而不是狗。
发布于 2022-01-13 17:38:45
有几种方法可以做到这一点。无论哪种方式,你必须在动物的名字和身份之间有某种关系。下面是一个基本的类
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保存一张动物名单
Private animals As List(Of Animal)并将其植入
animals = New List(Of Animal)()
animals.Add(New Animal(1, "Dog"))
animals.Add(New Animal(2, "Cat"))
animals.Add(New Animal(3, "Fish"))--我提到的两种方式
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = animalsPrivate 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填充ComboBox
您仍然需要这个类来保持动物名称和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这两种方法都会产生相同的结果,但我会说DataSource更好,因为您只需获得ComboBox1。选择作为一个动物,只检索名称或ID,而不是使用一些LINQ来提取第二种情况下的ID。

https://stackoverflow.com/questions/70698995
复制相似问题