User Control validation group issue

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 reason when validating the two user controls’ validators fire.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This method also works:

Dim valGroup = String.format("{0}-validation", Guid.NewGuid())

rfv001.ValidationGroup = valGroup
rfv002.ValidationGroup = valGroup
rfv003.ValidationGroup = valGroup
rfv004.ValidationGroup = valGroup
rfv005.ValidationGroup = valGroup

btnSubmit.ValidationGroup = valGroup

You only need to set the values for the ValidationGroup manually.

Method 2

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

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x