寻找组合框项目

时间:2017-10-17 13:45:49

标签: vb.net combobox

对于这个问题,我做了一个简单的课程:

Public Class ListBoxEntry
    Public Property ID As Integer
    Public Property Text As String

    Public Overrides Function ToString() As String
        Return Text
    End Function
End Class

我创建了这个类的一些实例并将它们添加到组合框中:

...
While DR.Read
  LI = New ListBoxEntry
  LI.ID = DR("ID") ' ID is an integer value
  LI.Text = DR(Feldname) ' Feldname is a string
  cmbList.Items.Add(LI)
End While

我无法通过代码获得将组合框设置为特定值的工作代码。 例如。这些是我的三个条目(ID - Feldname):

1 - One    (value 1, shown text in combobox "One")
2 - Two    (value 2, shown text in combobox "Two")
3 - Three  (value 3, shown text in combobox "Three")

Combobox1.SelectedIndex = somehow(2) <- here I want to set the combobox to the second entry (2), so "two" is selected

我需要哪种代码安静?

1 个答案:

答案 0 :(得分:2)

您应该将类​​的实例添加到数组或集合中,然后将其绑定到ComboBox,例如

With ComboBox1
    .DisplayMember = "Text"
    .ValueMember = "ID"
    .DataSource = myList
End With

然后,您可以将ID值分配给SelectedValue的{​​{1}}属性,以选择带有ComboBox的项目,例如

ID

那将显示&#34; Two&#34;在控制中。

相关问题