ASP.NET enum dropdownlist validation

Posted by Arun Kumar on Stack Overflow See other posts from Stack Overflow or by Arun Kumar
Published on 2012-06-29T02:48:03Z Indexed on 2012/06/29 3:16 UTC
Read the original article Hit count: 231

Filed under:
|

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about ASP.NET