To Create a DropDown List from an ENUM

Jun 29, 2009 Posted by Lara Kannan
You have an 'enum' defined as follows:
public enum CompanyAddressType
{
Unknown = 0,
Primary = 1,
Warehouse = 2,
Distribution_Center = 3,
Cross_Dock = 4
}

You want to iterate through the list and put the data into an asp.net dropdownlist.

Here is the simple code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[] names = Enum.GetNames(typeof(CompanyAddressType));
var values = (CompanyAddressType[])Enum.GetValues(typeof(CompanyAddressType));
for (int i = 0; i < names.Length; i++)
{
DropDownListCompanyAddressType.Items.Add(
new ListItem(names[i], values.ToString()));
}
}
}

There are probably easier ways to do it, but this works.

Use the tips!

If you like this post, say thank!
Share
Labels: , ,

Post a Comment