Binding a Control to an Enum

Imagine you have an enum defined in your code like so:

enum ContractType
    Permanent = 1,
    Contract = 2,
    Internship = 99

Suppose we have a DropDownList on an ASP.NET page from which we'd like the user to select the appropriate ContractType.

<asp:DropDownList runat="server" DataTextField="Key" DataValueField="Value" id="MyDropDownList">

Obviously, we can't do something as simple as

MyDropDownList.DataSource = ContractType;

as ContractType is a type, not an object. Instead, we can create a simple helper function that uses the Enum.GetValues and Enum.GetNames methods in order to create a Hashtable object (consisting of keys - Permanent, Contract, etc, and values - 1, 2 etc).

public static Hashtable BindToEnum(Type enumType)
    // get the names from the enumeration
    string[] names = Enum.GetNames(enumType);
    // get the values from the enumeration
    Array values = Enum.GetValues(enumType);
    // turn it into a hash table
    Hashtable ht = new Hashtable();
    for (int i = 0; i < names.Length; i++)
        // note the cast to integer here is important
        // otherwise we'll just get the enum string back again
        ht.Add(names[i], (int)values.GetValue(i));
    // return the dictionary to be bound to
    return ht;

You can then use this as follows:

MyDropDownList.DataSource = BindToEnum(typeof(ContractType));

and we get a drop down list bound to the appropriate names/values as defined by the enum (note that we specified DataTextField and DataValueField in the earlier DropDownList definition).

You might also like...


James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In order to understand recursion, one must first understand recursion.”