繁体   English   中英

选择项目后更改 Vb.net DropDownStyle Combobox 中的文本

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

在 vb.net 中选择某些内容后,如何更改 combobox 中显示的文本? 例如,如果用户从列表中选择“狗”,它将显示数字 1 而不是狗。

有几种方法可以做到这一点。 无论哪种方式,您都必须在动物名称和 id 之间建立某种关系。 所以这是一个基本的 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

保留动物清单

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"))

我提到的两种方法

  1. 将此列表用作数据源
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. 使用字符串名称填充 ComboBox

您仍然需要 class 来保持动物名称和 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.SelectedValue 作为动物,并简单地检索名称或 ID,而不是使用一些 LINQ 在第二个中提取 ID案子。

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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