簡體   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