Introduction
Do you have tons of enum
s like I do? Are you tired of having to manually add those values to your dropdowns, and then update them manually every time you update your enum
s? No more! Bind your controls to your enum
s so that they will update dynamically should you ever have to change them.
Using the Code
What I've done is basically written a simple, reuseable function you can put in a module somewhere and call any time you need to turn an enum
into workable data. Of course you can modify this code to return any sort of data you want, like an array list, a List(of) something, a DataSet
, etc. Simply supply an instance of your enum
and its type, and that's all!
The example I've given binds a combobox
for a Windows app. However, the
GetDataFromEnum
function will work anywhere.
I've heavily commented the code so you can see exactly what's going on at all times.
Public Enum SomeEnum
Bing
Bang
Bongo
End Enum
Public Function GetDataFromEnum(ByVal enumlist As System.Enum, ByVal enumtype As Type) _
As DataTable
Dim dt As New DataTable
dt.Columns.Add("value", GetType(Integer))
dt.Columns.Add("text", GetType(String))
Dim row As DataRow
Dim values As Array = System.Enum.GetValues(enumtype)
Dim names As Array = System.Enum.GetNames(enumtype)
For i As Integer = 0 To names.GetUpperBound(0)
row = dt.NewRow
row("value") = values(i)
row("text") = names(i)
dt.Rows.Add(row)
Next
Return dt
End Function
Public Sub Main()
dim list as SomeEnum
ComboBox1.DisplayMember = "text"
ComboBox1.ValueMember = "value"
ComboBox1.DataSource = GetDataFromEnum(list, GetType(SomeEnum))
End Sub
Easy as pie, cake, or even piecakes!
History
- 16th May, 2007: Original article posted