You can bind to a List(Of Item) as follows:
Dim ItemList = New List(Of Item) ' Fill the list with appropiate values.' listbox1.DataSource = ItemList listbox1.DisplayMember = "Name" listbox1.ValueMember = "ID"
Then listbox1.SelectedValue contains the ID , and you can access this name:
DirectCast(listbox1.SelectedItem, Item).Name
If you want to show both ID and Name , I suggest you add a property displayed in the Item class:
Public ReadOnly Property DisplayedValue() as String Get Return Me.Name & " (" & Me.ID.ToString & ")" End Get End Property
Then when linking the make list
listbox1.DisplayMember = "DisplayedValue"
Update:
Based on your comments below, I would say that my solution still works. However, using this methodology, items must be added to the list, and then the list associated with the object. Elements cannot be added separately and directly to the list box (since you will separate data from the presentation, I do not see a problem in this).
To display a message box with the selected item, you just need to do:
MessageBox.Show(DirectCast(listbox1.SelectedItem, Item).ID.ToString))
source share