How do I bind an enum to a combo box

  • Thread starter Thread starter phillip_putzback
  • Start date Start date
P

phillip_putzback

And get both the value and name of the enum.

So when the user drops down a selects red from the combo box I can see
the selectedvalue as 1.

I am tinkering with fieldinfo.name and fieldinfo.metadatatoken to get
these values right now.

Thanks.
 
Hi Philip
In the following code snippet, you can pass an enum to an instance
EnumDataSource class and then set this instance to datasource of combo
box :

Public Class EnumDataSource

Public EnumItems As New List(Of NameValuePair)
Sub New(ByVal e As Type)
CreateList(e)
End Sub

Sub CreateList(ByVal e As Type)
Dim stringItems() As String
stringItems = [Enum].GetNames(e)
For Each item As String In stringItems

EnumItems.Add(New NameValuePair(item, [Enum].Parse(e,
item)))
Next
End Sub



End Class

Public Class NameValuePair
Private m_Name As String
Private m_Value As Integer

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal value As String)
m_Name = value
End Set
End Property

Public Property Value() As Integer
Get
Return m_Value
End Get
Set(ByVal value As Integer)
m_Value = value
End Set
End Property
Sub New(ByVal name As String, ByVal value As Integer)
Me.Name = name
Me.Value = value
End Sub

Public Overrides Function ToString() As String
Return Name
End Function

End Class


---------------------------------
usage :

Public Enum Colors
Red
Blue
Green
Yellow

End Enum


' Binding
Dim c As Colors
Dim l As New EnumDataSource(c.GetType())
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "Value"
ComboBox1.DataSource = l.EnumItems


' get selected
MsgBox(ComboBox1.SelectedValue)
MsgBox(ComboBox1.SelectedItem.ToString())


Best Regards,
A.Hadi
 
Back
Top