Today I m faced a problem when I want to re-use Enum without major change on the based code.
Here the simple example,
I got a drop down list which bind Enum, here the sample code:
public enum Gender
{
[Description("I m a Male")] M,
[Description("I m a Female")] F
}
if you just bind the Enum, your dropdownlist will simply show you “M” and “F”, what if I want to show “I m a Male” and “I m a Female”?
OK, here the trick. (I will put the Author URL once I found, I m forgot the link)
in PageLoad or Code Behind,
using System.ComponentModel;
using System.Reflection;
public static string GetDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}
Here you will see gender.ToString(“d”), it will return 0 or 1, if you simply put ToString(), it will return M or F
foreach (Gender gender in Enum.GetValues(typeof(Gender)))
{
this.ddlGender.Items.Add(new ListItem(GetDescription(gender ), gender.ToString("d")));
}
Hope this Help