RequiredFieldValidator for a dropdownlist

10.1k Views Asked by At

I have a dropdownlist which I am developing dynamically in the code.

  Dim objPreferenceDropdownList As DropDownList = New DropDownList()
                        objPreferenceDropdownList.ID = "objPreferenceDropdownList"
                        objPreferenceDropdownList.AppendDataBoundItems = "True"

              objPreferenceDropdownList.AutoPostBack = True

I am populating this dropdown with different items such as

objPreferenceDropdownList.Items.Add(new ListItem("--Select Color--","0"));

 objPreferenceDropdownList.Items.Add(new ListItem("Red","1"));

 objPreferenceDropdownList.Items.Add(new ListItem("Blue","2"));

objPreferenceDropdownList.Items.Add(new ListItem("White", "3"));

objPreferenceDropdownList.Items.Add(new ListItem("Pink", "4"));

Now I need to validate the dropdownlist it there is no any item selected in the dropdown for that I created a required field validator dynamically like this:

Dim reqPrefGroupValidator As RequiredFieldValidator = New RequiredFieldValidator()
                                reqPrefGroupValidator.ControlToValidate = "objPreferenceDropdownList"
                                reqPrefGroupValidator.InitialValue = "0"
                                reqPrefGroupValidator.SetFocusOnError = True
                                prefdiv.Controls.Add(reqPrefGroupValidator)

The problem is required field validator only works when dropdownlist is empty what if I need to fire requiredfieldvalidator when the selected item value of dropdownlist is zero.

2

There are 2 best solutions below

0
On BEST ANSWER

Set the InitialValue of the validator to 0 and the validator must have and ID ofcourse as:

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
        ErrorMessage="RequiredFieldValidator" ControlToValidate="objPreferenceDropdownList" 
        InitialValue="0"></asp:RequiredFieldValidator>
1
On

you can use Compare Field Validator and CompareValue to 0 and CompareType int.

you can do this way.

<asp:DropDownList runat="server" ID="objPreferenceDropdownList"></asp:DropDownList>
    <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="plz Select Value" ValueToCompare="0" Operator="GreaterThan" ControlToValidate="objPreferenceDropdownList" Type="Integer"></asp:CompareValidator>
    <asp:Button ID="btnSubmit" runat="server" Text="Submit Form" OnClick="btnSubmit_Click" />