User Control validation group issue

前端 未结 2 1044
一个人的身影
一个人的身影 2020-12-18 06:27

I have two instances of a user control on a page. Both have fields and one submit button.

I have set validation groups on the fields and validators but for some reas

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-18 06:56

    You could expose a property ValidationGroup in your UserControl that you would set from the Page. This value should be stored in ViewState, so that every instance of the UserControl will get different ValidationGroups(if your page assigns different).

    For example:

    Public Property ValidationGroup() As String
     Get
      Return CStr(ViewState("ValidationGroup"))
     End Get
     Set(ByVal value As String)
      SetValidationGroupOnChildren(Me, value)
      ViewState("ValidationGroup") = value
     End Set
    End Property
    
    Private Sub SetValidationGroupOnChildren(ByVal parent As Control, ByVal validationGroup As String)
        For Each ctrl As Control In parent.Controls
            If TypeOf ctrl Is BaseValidator Then
                CType(ctrl, BaseValidator).ValidationGroup = validationGroup
            ElseIf TypeOf ctrl Is IButtonControl Then
                CType(ctrl, IButtonControl).ValidationGroup = validationGroup
            ElseIf ctrl.HasControls() And ctrl.Visible = True Then
                SetValidationGroupOnChildren(ctrl, validationGroup)
            End If
        Next
    End Sub
    
    • http://www.craigwardman.com/blog/index.php/2009/05/setting-a-validation-group-on-a-user-control/
    • http://justgeeks.blogspot.com/2009/09/be-careful-using-hard-coded.html

    If you need different ValidationGroups in your UserControl the above recursive function won't work, then you could assign it manually from codebehind. For example by putting the UserControl's ID(might suffice) or ClientID in front of the ValidationGroup properties of the according controls. A good place where you could call this function would be PreRender.

提交回复
热议问题