This came up when I was writing a UIProperty for SmartCodeGenerator,
The combo box should display all the available enum options in a DropDownList for the enduser to choose from them.
So if someone defines a enum like this:
public enum MyEnum
{
ten = 10,
twenty = 20 ,
thirty = 30
}
and a class using the enum as one of its property, ie.
public class TheProperties
{
public TheProperties( )
{
//Please Assign Default Values here
this.myVar = MyEnum.twenty;
}
private MyEnum testEnumProp;
public MyEnum TestEnumProp
{
get { return testEnumProp; }
set { testEnumProp = value; }
}
}
For this declaration above my Objective is to comeup with a ASP.Net DropDownList with the endresult in html like this:
<select name="MyVar$ddProperty" id="MyVar_ddProperty">
<option value="10">ten</option>
<option selected="selected" value="20">twenty</option>
<option value="30">thirty</option>
</select>
Ok here is the code to achieve this:
object profile = new TheProperties();
foreach (PropertyInfo propertyInfo in profile.GetType().GetProperties())
{
if ((info.PropertyType.IsEnum) && (info.PropertyType.IsPublic))
{
foreach (FieldInfo fInfo in this.propertyInfo.PropertyType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
//ListItem item = new ListItem(fInfo.Name, ((int)fInfo.GetValue(this.propertyInfo)).ToString());//.Net1.1
ListItem item = new ListItem(fInfo.Name, fInfo.GetRawConstantValue().ToString());
ddProperty.Items.Add(item);
}
}
}
in .Net2.0 we have this nice little function GetRawConstantValue() which returns the value associated with enum (in this example 10, 20, 30)
in .Net1.1 we have to do it in old fashioned way with the GetValue(...) method.