Add items with value and text to a combobox

C

cowznofsky

I was databinding to a combobox and supplying both a DisplayMember and
a ValueMember,
so that each item.

Now I've decided against databinding, and will populate it by going
through a datatable.

What's the easy way to populate it so that each item has both a value
and a text?

Also, once populated, what's the easy way to find items without setting
the selectedIndex?
 
T

Tim Patrick

Try the following class.

Public Class ListItemData
' ----- Class used to support ListBox and ComboBox items.
Public ItemText As String
Public ItemData As Long

Public Sub New(ByVal newText As String, ByVal newData As Long)
' ----- Required constructor.
ItemText = newText
ItemData = newData
End Sub

Public Overrides Function ToString() As String
' ----- Show the text in ListBox and ComboBox displays.
Return ItemText
End Function

Public Overrides Function Equals(ByVal obj As Object) As Boolean
' ----- Allow IndexOf() and Contains() searches by ItemData.
If (TypeOf obj Is Long) Then
Return CBool(CLng(obj) = ItemData)
Else
Return MyBase.Equals(obj)
End If
End Function
End Class

Add items to your listbox using the following code.

ListBox1.Items.Add(New ListItemData(someText, someNumericValue))

When you want to locate an item by its numeric value, use this code:

position = ListBox1.Items.IndexOf(someNumericValue)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top