我有一个动态列表框,我想添加一个动态验证器控件,以便用户必须从列表框中选择2个选项 - 不多也不少。我玩过rangevalidator和regularexpressionvalidator控件,但它们没有用。 有没有人在那里做过这件事?
答案 0 :(得分:3)
您必须编写自定义验证程序。
答案 1 :(得分:0)
您必须编写自定义验证程序,然后在按钮单击事件或任何此类事件上添加类似于您的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
答案 2 :(得分:0)
自定义验证器很好......但代码非常简单:
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
您实际上并不需要遍历列表并单独评估所有控件。