Skip to content

A Quick Tip – On Binding Enums to a DropdownList

January 13, 2012

Here’s a really handy tip for binding an enum to a DropDownList component in ASP.NET, all you need to do is to write a HashTable with your enumerated type, and convert the value, and key of that enumeration to the Hashtable object and set it as the datasource of the DropdownbList. Here’s how: –

protected void Page_Load(object sender, EventArgs e)
{
Hashtable ht = GetEnumForBind(typeof(YourEnum));
DropDownList1.DataSource = ht;
DropDownList1.DataTextField = “value”;
DropDownList1.DataValueField = “key”;

DropDownList1.DataBind();

}

public Hashtable GetEnumForBind(Type enumeration)
{
string[] names = Enum.GetNames(enumeration);
Array values = Enum.GetValues(enumeration);
Hashtable ht = new Hashtable();
for (int i = 0; i < names.Length; i++)
{
ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
}
return ht;
}

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: