开发者

Which validator control to use to limit a listbox selections to 2?

I have a dynamic listbo开发者_JAVA百科x and I'd like to add a dynamic validator control so that the user must select 2 options from the listbox - no more, no less. I've played around with the rangevalidator and the regularexpressionvalidator controls but they didn't work. Has anybody out there done this before?


You will have to write a custom validator.


A custom validator is fine...but the code is very simple:

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

You don't actually need to traverse the list and evaluate all of the controls individually.


You will have to write a custom validator and then on button click event or any such event add a validation group similar to your customvalidator group.

In the code behind I am finding my checkbox from a gridview and checking if more items are selected or not.

    <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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜