将枚举转换为 DataTables






3.79/5 (9投票s)
2004年8月25日

57446
关于将枚举转换为 DataTables 的文章。
引言
这只是一个将 Enum
转换为 DataTable
的快速技巧,不确定是否有任何实际用途。由于只是一个代码片段,没有可下载的项目,您可以从此页面复制并粘贴即可使用,嗯…… 告诉我您对此的看法。
使用代码
好的,现在开始吧,正如我提到的,只需复制并粘贴即可。请记住,要调用该函数,您需要对枚举使用 GetType
,例如:
EnumToDataTable(GetType(EnumerationName) , "", "")
' Test enumeration
Private Enum ETestEnum
Enum_Item_A = 0
Enum_Item_B = 1
Enum_Item_C = 2
End Enum
'--------------------------------------------------------
' Use this little function to test it
'--------------------------------------------------------
Private Sub Test()
Dim oData As DataTable
' Notice that we must use 'GetType(Enumeration)'
oData = EnumToDataTable(GetType(ETestEnum), "KEY", "VALUE")
End Sub
现在是真正的代码:
'-------------------------------------------
' Desription: Convert a given enum into a datatable
'
' Parameters: EnumObject - type of the enum
' KeyField - name for the key column, if not
' supplied it will be set to "KEY"
' ValueField - name for the vaue column, if not
' supplied it will be set to "VALUE"
'--------------------------------------------
Public Function EnumToDataTable(ByVal EnumObject As Type, _
ByVal KeyField As String, ByVal ValueField As String) As DataTable
Dim oData As DataTable = Nothing
Dim oRow As DataRow = Nothing
Dim oColumn As DataColumn = Nothing
'-------------------------------------------------------------
' Sanity check
If KeyField.Trim() = String.Empty Then
KeyField = "KEY"
End If
If ValueField.Trim() = String.Empty Then
ValueField = "VALUE"
End If
'-------------------------------------------------------------
'-------------------------------------------------------------
' Create the DataTable
oData = New DataTable
oColumn = New DataColumn(KeyField, GetType(System.Int32))
oData.Columns.Add(KeyField)
oColumn = New DataColumn(ValueField, GetType(System.String))
oData.Columns.Add(ValueField)
'-------------------------------------------------------------
'-------------------------------------------------------------
' Add the enum items to the datatable
For Each iEnumItem As Object In [Enum].GetValues(EnumObject)
oRow = oData.NewRow()
oRow(KeyField) = CType(iEnumItem, Int32)
oRow(ValueField) = StrConv(Replace(iEnumItem.ToString(), "_", " "), _
VbStrConv.ProperCase)
oData.Rows.Add(oRow)
Next
'-------------------------------------------------------------
Return oData
End Function