The simple way round this is to bind the combobox to a collection of objects. When binding a combobox, you specify the source (the collection), the name of the display member and the name of the value member. The names you specify correspond to the names of the properties of the object.
So, we need to create a two classes; one for each item in the combobox, and another generic collection class to group them all together and serve as the data source. Let's get started.
In my example, the item class represents a state. Each state has a long name, and a short name, as used in printed street addresses. The class just contains two properties and a simple constructor.
Expand|Select|Wrap|Line Numbers
- Public Class State
- Private _ShortName As String
- Public Property ShortName() As String
- Get
- Return _ShortName
- End Get
- Set(ByVal value As String)
- _ShortName = value
- End Set
- End Property
- Private _LongName As String
- Public Property LongName() As String
- Get
- Return _LongName
- End Get
- Set(ByVal value As String)
- _LongName = value
- End Set
- End Property
- Public Sub New(ByVal shortName As String, ByVal longName As String)
- Me.ShortName = shortName
- Me.LongName = longName
- End Sub
- End Class
Expand|Select|Wrap|Line Numbers
- Public Class States
- Inherits CollectionBase
- Public Sub New()
- InnerList.Add(New State("QLD", "Queensland"))
- InnerList.Add(New State("NSW", "New South Wales"))
- InnerList.Add(New State("VIC", "Victoria"))
- InnerList.Add(New State("TAS", "Tasmania"))
- InnerList.Add(New State("WA", "Western Australia"))
- InnerList.Add(New State("SA", "South Australia"))
- InnerList.Add(New State("NT", "Northern Territory"))
- InnerList.Add(New State("ACT", "Australian Capital Territory"))
- InnerList.Sort(New StatesComparer)
- End Sub
- Friend Class StatesComparer
- Implements IComparer
- Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
- If TypeOf (x) Is State And TypeOf (y) Is State Then
- Return DirectCast(x, State).LongName < DirectCast(y, State).LongName
- Else
- Throw New Exception("Object is not of type State")
- End If
- End Function
- End Class
- End Class
Now I have my populated and sorted collection of items, all I need to do is to bind my combobox to it. It doesn't really matter where one does this, provided it is called before the combobox is needed.
Expand|Select|Wrap|Line Numbers
- Dim comboStates As New ComboBox()
- comboStates.DataSource = New States
- comboStates.DisplayMember = "LongName"
- comboStates.ValueMember = "ShortName"