Wednesday, March 26, 2008

How to fill drop-down box with Enum values

A code snipet from http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=420
(see this code as well)

Suppose you have enum PersonType and want to populate lstPersonType drop-down box with its values.
It is very easy with Reflection:

public enum PersonType {
Friend = 0,
Family = 1,
Colleague = 2,
NotSet = -1
}

private void BindTypeDropDown()
{
FieldInfo[] myEnumFields = typeof(PersonType).GetFields();
foreach (FieldInfo myField in myEnumFields)
{
if (!myField.IsSpecialName && myField.Name.ToLower() != "notset")
{
int myValue = (int)myField.GetValue(0);
lstPersonType.Items.Add(new ListItem(myField.Name, myValue.ToString()));
}
}
}