使用哪个验证器控件将列表框的选择限制为2
本文关键字:选择 列表 验证 控件 | 更新日期: 2023-09-27 18:03:26
我有一个动态列表框,我想添加一个动态验证器控件,以便用户必须从列表框中选择2个选项-不多也不少。我玩过的范围验证器和正则表达式验证器控件,但他们没有工作。以前有人这样做过吗?
您必须编写一个自定义验证器
自定义验证器很好…但是代码非常简单:
Protected Sub myCustomVal(ByVal sender As Object, ByVal e As ServerValidateEventArgs)
If ListBox1.GetSelectedIndices.Length =2 THEN
e.isvalid = true
Else
e.isvalid = false
end if
End Sub
您实际上不需要遍历列表并单独计算所有控件。
您必须编写一个自定义验证器,然后在按钮单击事件或任何此类事件时添加一个类似于您的customvalidator组的验证组。
在后面的代码中,我从gridview中找到我的复选框,并检查是否选择了更多的项目。
<asp:CustomValidator ID="customValidatorForCheckboxlist"
runat="server" ErrorMessage="Required Field" ValidationGroup="valSurvey"
OnServerValidate="CheckifCheckBoxHasMoreItems" SetFocusOnError="true" Display="Dynamic"></asp:CustomValidator>
Protected Sub CheckifCheckBoxHasMoreItems(ByVal sender As Object, ByVal e As ServerValidateEventArgs)
'This code block is for custom Validator known as customValidatorForCheckboxlist
Dim count As Integer
For Each gvrow As GridViewRow In gridview1.Rows
'Initialize a New instance of ContextAttributeArtifacts and ContextAttributesArtifactsOpenEnded and Assign Properties to Them.
For Each ct As Control In gvrow.Cells(1).Controls
If ct.GetType.ToString().Equals("System.Web.UI.WebControls.CheckBoxList") Then
Dim _checkboxlist As CheckBoxList = DirectCast(ct, CheckBoxList)
For Each ListItem1 As ListItem In _checkboxlist.Items
If ListItem1.Selected = True Then
valbool = True
count = count + 1
End If
Next
End If
Next
Next
If count > 2 Then
e.IsValid = False
ElseIf count < 2 Then
e.IsValid = True
End If
End Sub