Turn an Enum into a DataTable
Need to bind controls to pre-set enums? Here's how!
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 'create your enum
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)) 'set your table up
dt.Columns.Add("text", GetType(String))
Dim row As DataRow
'get the values from your enum, i.e. 1, 2, 3, etc.
Dim values As Array = System.Enum.GetValues(enumtype)
'get the string values (Bing, Bang, and Bongo in this example)
Dim names As Array = System.Enum.GetNames(enumtype)
For i As Integer = 0 To names.GetUpperBound(0)
row = dt.NewRow 'build a row in the format of the table
row("value") = values(i) 'put values in your row
row("text") = names(i) 'put strings in your row
dt.Rows.Add(row) 'add row to table
Next
Return dt 'return full table of enum values!
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