RequiredFieldValidator for the drop down list

I have a drop-down list that I am dynamically developing in code.

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

I fill this drop-down menu with various elements 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 check that there is not a single item in the drop-down list selected in the drop-down list for which I created the necessary field validator dynamically as follows:

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

The task is required. Validator only works if the drop-down list is empty, if I need to remove the required identifier when the value of the selected dropdownlist element is zero.

+4
source share
2 answers

Set the Validator's InitialValue to 0, and the validator should have a session identifier as:

 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ControlToValidate="objPreferenceDropdownList" InitialValue="0"></asp:RequiredFieldValidator> 
+12
source

you can use Compare Validator and CompareValue at 0 and CompareType int.

You can do it.

 <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" /> 
+1
source

Source: https://habr.com/ru/post/1392188/


All Articles