1

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.

3 Answers 3

2

Add a please specify before adding the enum items.

 TypeDropDownList.Items.Add("Please Specify","");
 foreach (TypeDesc newPatient in EnumToDropDown.EnumToList<TypeDesc>())
 {
    TypeDropDownList.Items.Add(EnumToDropDown.GetEnumDescription(newPatient), newPatient.ToString());
 }

Remove "Please Specify" from the enum

Sign up to request clarification or add additional context in comments.

4 Comments

But I am saving my enum value as tinyint in my database. If I remove "Please Specify" from enum it will save 0 for Auckland in my database and I don't want that
well you can start the enum from 1 Auckland=1
I did that it works this way for all values except "Palmerston North". visual studio through as Jscript error for validator given below:Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: 'TypeDropDownList' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value
Thanks for that I sorted it out.... our code is almost the same.... please refer to my answer...... thanks for the help
0

DropDownList can bind to a Value and Text property when explicitly specified. When the value for an item is null, this will be picked up by your validator.

<asp:DropDownList ID="TypeDropDownList" runat="server" DataTextField="Text" DataValueField="Value" ></asp:DropDownList>

and when adding items:

foreach (TypeDesc newPatient in EnumToDropDown.EnumToList<TypeDesc>())
{
   string text = EnumToDropDown.GetEnumDescription(newPatient)),
   TypeDropDownList.Items.Add(new
   {
       Text = text,
       Value = text == "Please specify" ? null : text // should be replaced with a clean solution
   }
}

4 Comments

What would be a cleaner solution?
didn't work through a Jscript error: Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: 'TypeDropDownList' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value
@tsukimi - Assign an attribute like System.ComponentModel.DataAnnotations.KeyAttribute and when set, use that value as the value
@ArunKumar - Sorry, you have to use an empty string.
0

I sorted it out I used the following code

if (TypeDropDownList.Items.Count == 0)
            {
                foreach (TypeDesc newPatient in EnumToDropDown.EnumToList<TypeDesc>())
                {
                    string text = EnumToDropDown.GetEnumDescription(newPatient);

                    TypeDropDownList.Items.Add(new ListItem(text, newPatient.ToString()));
                }
            }

and the validator as

<asp:RequiredFieldValidator ID="TypeRequiredValidator" runat="server" ControlToValidate="TypeDropDownList"
                InitialValue="PleaseSpecify" ErrorMessage="Please Select a City" Text="<img src='Styles/images/Exclamation.gif' />"
                ValidationGroup="city"></asp:RequiredFieldValidator>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.