ASP.NET enum dropdownlist validation
- by Arun Kumar
I have got a enum
public enum TypeDesc
{
[Description("Please Specify")]
PleaseSpecify,
Auckland,
Wellington,
[Description("Palmerston North")]
PalmerstonNorth,
Christchurch
}
I am binding this enum to drop down list using the following code on page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (TypeDropDownList.Items.Count == 0)
{
foreach (TypeDesc newPatient in EnumToDropDown.EnumToList<TypeDesc>())
{
TypeDropDownList.Items.Add(EnumToDropDown.GetEnumDescription(newPatient));
}
}
}
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
public static IEnumerable<T> EnumToList<T>()
{
Type enumType = typeof(T);
// Can't use generic type constraints on value types,
// so have to do check like this
if (enumType.BaseType != typeof(Enum))
throw new ArgumentException("T must be of type System.Enum");
Array enumValArray = Enum.GetValues(enumType);
List<T> enumValList = new List<T>(enumValArray.Length);
foreach (int val in enumValArray)
{
enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
}
return enumValList;
}
and my aspx page use the following code to validate
<asp:DropDownList ID="TypeDropDownList" runat="server" >
</asp:DropDownList>
<asp:RequiredFieldValidator ID="TypeRequiredValidator" runat="server" ControlToValidate="TypeDropDownList" ErrorMessage="Please Select a City" Text="<img src='Styles/images/Exclamation.gif' />"
ValidationGroup="city"></asp:RequiredFieldValidator>
But my validation is accepting "Please Specify" as city name. I want to stop user to submit if the city is not selected.