我有一个下拉列表,我在代码中动态开发。
Dim objPreferenceDropdownList As DropDownList = New DropDownList()
objPreferenceDropdownList.ID = "objPreferenceDropdownList"
objPreferenceDropdownList.AppendDataBoundItems = "True"
objPreferenceDropdownList.AutoPostBack = True
我使用不同的项目填充此下拉列表,例如
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"));
现在我需要验证下拉列表,它没有在下拉列表中选择任何项目,因为我动态创建了一个必需的字段验证器:
Dim reqPrefGroupValidator As RequiredFieldValidator = New RequiredFieldValidator()
reqPrefGroupValidator.ControlToValidate = "objPreferenceDropdownList"
reqPrefGroupValidator.InitialValue = "0"
reqPrefGroupValidator.SetFocusOnError = True
prefdiv.Controls.Add(reqPrefGroupValidator)
问题是必填字段验证器仅在dropdownlist为空时才有效,如果我需要在下拉列表的选定项目值为零时触发requiredfieldvalidator。
答案 0 :(得分:12)
将验证器的InitialValue设置为0,验证器必须具有ID和ofcourse:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="RequiredFieldValidator" ControlToValidate="objPreferenceDropdownList"
InitialValue="0"></asp:RequiredFieldValidator>
答案 1 :(得分:1)
您可以使用Compare Field Validator和CompareValue为0和CompareType int。
你可以这样做。
<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" />