Visual Basic.NET 7.x (2002/03)Visual Studio .NET 2002Visual Basic 8 (2005).NET 1.0Visual Studio .NET 2003WebForms.NET 1.1.NET 3.0Visual Studio 2005.NET 2.0Windows Forms中级开发Visual StudioWindows.NETVisual BasicASP.NET
将 Enum 转换为 DataTable
需要将控件绑定到预设的 enum?
引言
你有没有像我一样大量的enum
s?你是否厌倦了必须手动将这些值添加到你的下拉列表中,然后在每次更新enum
s时手动更新它们?不再需要了!将你的控件绑定到你的enum
s,这样它们会在你不得不更改它们时动态更新。
Using the Code
我所做的是基本上编写了一个简单的、可重用的函数,你可以把它放在某个模块中,并在任何需要将一个enum
转换为可用的数据时调用它。当然,你可以修改这段代码以返回任何你想要的数据,比如一个数组列表、一个List(of) 某个类型、一个DataSet
等等。只需提供你的enum
的实例及其类型,就完成了!
我给出的例子绑定了一个Windows应用程序的combobox
。但是,GetDataFromEnum
函数可以在任何地方工作。
我已对代码进行了大量注释,以便你可以随时了解正在发生的事情。
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
就像切派、蛋糕,甚至派蛋糕一样简单!
历史
- 2007年5月16日:发布原始文章