Monday, August 23, 2010

bind Enum to drop down list in ASP.NET

This the question asked by so many people around me and I also faced issues couple of times of my early stages of learning.This is simple but, how to get value and names as a collection and bind to drop down list is a bit difficult. Below is the simple logic to read all enums and create a list item and bind to drop down list. [There are many ways to get this done, but I believe below is the best way.]
foreach (UserType ut in Enum.GetValues(typeof(UserType)))
{
ListItem item = new ListItem(Enum.GetName(typeof(UserType), ut), ((int)ut).ToString("D"));
ddlUserType.Items.Add(item);
}
I think, you like this post. Let me know if you have any issues.

2 comments:

  1. Please use ut.ToString("D"). It is better.

    ReplyDelete
  2. Hi Johnnie,
    Thanks for the comment. I have added the format specifier to ToString().

    -Praveen.

    ReplyDelete