Tuesday, June 16, 2009

To Create a DropDownList from an ENUM

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!