Bind DropDownList to Enum

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

Comments

Leave your comment

Author

Email (never displayed)

Website

Comment  
HTML is NOT allowed. Use regular line breaks and those will be respected.