Stefan Meyer
Stefan Meyer

Reputation: 928

Finding combobox item

For this question I made a simple class:

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

I create some instances of this class and add them into a combobox:

...
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

I cannot get a working code for setting the combobox to a specific value by code. E.g. these are my three entries (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

Which peace of code to I need?

Upvotes: 1

Views: 152

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54457

You should add the instances of your class to an array or collection, then bind that to your ComboBox, e.g.

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

You can then assign an ID value to the SelectedValue property of the ComboBox to select the item with that ID, e.g.

ComboBox.SelectedValue = 2

That would display "Two" in the control.

Upvotes: 2

Related Questions