Click here to Skip to main content
Click here to Skip to main content

Convert Enums to DataTables

By , 24 Aug 2004
 

Introduction

This is just a quick trick to convert an Enum into a DataTable, not sure if it would be of any practical use. There are no projects to download since is just a code snippet, copy and paste from this page and you are ready to go, well... let me know what you think about it.

Using the code

Ok here it goes, as I mentioned just copy and paste, remember that to call the function you will have to use the GetType on the enumeration i.e.:

  • 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

Now here comes the real code

'-------------------------------------------
' 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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

ferran9
United Kingdom United Kingdom
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralThis will Create a List of Enum in a ListBoxmemberaaroncampf24 Nov '10 - 12:46 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim test As DataTable = EnumToDataTable(GetType(Aaron.Aaron_Components.Mod_Enum.Master_Tools.Tools_List), "", "")
 
ListBox1.Items.Clear()
For Each Item As System.Data.DataRow In test.Rows
ListBox1.Items.Add(Item.Item(1))
Next
 
End Sub
GeneralC#memberRipplingCreek8 Jul '08 - 7:58 
        /// <summary>
        /// Converts an enum to a DataTable.
        /// </summary>
        /// <param name="enumType">The enum to convert.</param>
        /// <param name="keyFieldName">The desired name of the key column.</param>
        /// <param name="valueFieldName">the desired name of the value column.</param>
        /// <returns>A DataTable with the name/value pairs from the enum.</returns>
        public static DataTable EnumToDataTable(Type enumType, string keyFieldName, string valueFieldName)
        {
            //Check inputs: 

            if (keyFieldName == String.Empty)
                keyFieldName = "Key";
 
            if (valueFieldName == String.Empty)
                valueFieldName = "Value";
 
            if (keyFieldName == valueFieldName)
                throw new Exception("Key and Value column names must be different.");
 
            //Create the DataTable with the desired columns:

            DataTable table = new DataTable();
 
            table.Columns.Add(keyFieldName, typeof(string));
            table.Columns.Add(valueFieldName, Enum.GetUnderlyingType(enumType));
 
            //Add the items from the enum:

            foreach (string name in Enum.GetNames(enumType))
            {
                table.Rows.Add(name, Enum.Parse(enumType, name));
            }
 
            return table;
        }

GeneralExcellent for populating options...memberGlimmerMan5 Sep '06 - 7:01 
I am using Dart FTP component and wanted to allow users to change security options under Dart.PowerTCP.SecureFtp.Security enumeration from a ComboBox, this code works great for that, simply set the datasource and DisplayMember.
 
To convert back again
System.ComponentModel.TypeDescriptor.GetConverter(myEnum).ConvertFromString(DomainUpDown1.SelectedItem.ToString)
 
Thanks for sharing!!!
 
Kevin S. Gallagher
Programming is an art form that fights back

GeneralUsesmemberstixoffire11 Jul '06 - 4:16 
As a Newbie to Coding in .NEt and in general coding OOP.
 
What uses would I use something like this for ?Big Grin | :-D
GeneralI agreememberRicardo Casquete17 Feb '06 - 23:36 
I think it could be interesting to load and bind data in a combo, listBox...
 
Ricardo Casquete

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 25 Aug 2004
Article Copyright 2004 by ferran9
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid