hello. A question please. If I add elements to a combobox manually, I mean for example
combobox.Items.Add(
"Monday")Can I associate a key to each element of my combox
Something like this:
ComboBox1.DataSource = datatable
ComboBox1.DisplayMember = "long_name"
ComboBox1.ValueMember = "id"
Thanks in advance...

Combobox question
db_guy
I arrive with another question on the same thing, I guess. Could I access to an element of the combobox with a ID I mean. The example given works excelent if the SelectedIndexChanged occurs, but what happens if I have an ID which is retrieved of a table Is there a way to access directly to the object (ID,Name) of the combobox passing the ID and without reading all elements....
Thanks in advance...
jamie r
spin_n
not entirely, you can only do that (what you showed) when binding. the ValueMember and DisplayMember can only be used, AFAIK, when you set the DataSource of the bindable control.
Can you explain exactly what you are trying to do
Jamie Thomson
Tom Nash
I think you would have to iterate through the collection to identify locate the index number of a specific ID number.
All the collection knows is its a collection of objects which have a tostring method.
lord_8
Nicolas2608
trickhat
Thank you very much, but it is not what I'd want. The example I gave is generic. What happens if I process lettres Another idea
Thanks...
Kutlu Araslı
This is really simple and doesnt require databinding. If you implement any class (in my case ListItem) and as long as you have a Public Overide on the tostring method - this is what will be displayed in the listbox/combobox etc.
When you retrieve the selected item - you can cast it to the original object type and access all the specific properties such as ID, Name etc.
Here's an example which does just what you talking about.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim x As New ListItem("abc", 1)
Me.ComboBox1.Items.Add(x)
x = New ListItem("def", 2)
Me.ComboBox1.Items.Add(x)
x = New ListItem("ghi", 3)
Me.ComboBox1.Items.Add(x)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim x As ListItem = Me.ComboBox1.SelectedItem
Dim s As String = x.ID & vbCrLf & x.Name
MsgBox(s)
End Sub
End Class
Public Class ListItem
Private StrItemName As String = ""
Private IntID As Integer
Public ReadOnly Property Name() As String
Get
Return StrItemName
End Get
End Property
Public ReadOnly Property ID() As Integer
Get
Return IntID
End Get
End Property
Public Overrides Function ToString() As String
Return StrItemName
End Function
Public Sub New(ByVal Name As String, ByVal ID As Integer)
StrItemName = Name
IntID = ID
End Sub
End Class