Displaying articles with tag databind

Bind DropDownList to Enum

Posted by gabriel, Tue Jul 01 22:12:00 UTC 2008

Unfortunately you can’t Databind an Enum to a DropDownList or to any control for that matter. You can however transform the Enum into something “bindable” like a HashTable.

First let’s define an Enum to use in our example:


public enum Cars
{
    Ford = 1,
    Kia = 2, 
    Mitsubishi = 3,
    Volkswagen = 4
}

Now let’s write a method that will read the enum and convert it into a HashTable.


    public Hashtable GetEnumForBind(Type enumeration)
    {
        //returns all the names in the enum
        string[] names = Enum.GetNames(enumeration);

        //return all the values in the enum
        Array values = Enum.GetValues(enumeration);

        Hashtable ht = new Hashtable();
        for (int i = 0; i < names.Length; i++)
        {
            //adds each item pair (value/name) to the Hash
            ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
        }
        return ht;
    }

Now that we have a method that will allow an enum to a HashTable all we need to do is bind the hash to the DropDownList.


        //call our previously defined method to create the HashTable
        Hashtable ht = GetEnumForBind(typeof(Cars));

        //set the HashTable as the DataSource
        DropDownList1.DataSource = ht;
        //set the value of the Hash as the display
        DropDownList1.DataTextField = "value";
        //set the key of the Hash as the value
        DropDownList1.DataValueField = "key";

        DropDownList1.DataBind();

That is it, it should now bind without problems. There are alternate solutions that do not involve binding but instead adding each item of the enum to the DropDownList. You can take a look at the asp.net forums to see alternate solutions proposed by other members.

0 comments | Filed Under: Tips and Tutorials | Tags: databind