简体   繁体   English

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

[英]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?在 vb.net 中选择某些内容后,如何更改 combobox 中显示的文本? For example, if the user picks "dog" from the list, it will display a number 1 instead of dog.例如,如果用户从列表中选择“狗”,它将显示数字 1 而不是狗。

There are a couple ways to do this.有几种方法可以做到这一点。 Either way, you must have some relationship between the animal name and id.无论哪种方式,您都必须在动物名称和 id 之间建立某种关系。 So here's a basic class所以这是一个基本的 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使用字符串名称填充 ComboBox

You do still need the class to keep a relationship between animal name and id您仍然需要 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

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.两种方法都会产生相同的结果,但我会说 DataSource 更好,因为您可以将 ComboBox1.SelectedValue 作为动物,并简单地检索名称或 ID,而不是使用一些 LINQ 在第二个中提取 ID案子。

在此处输入图像描述

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

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