Reputation: 7758
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.
Upvotes: 5
Views: 4459
Reputation: 2993
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.
Upvotes: 7
Reputation: 460048
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
.
Upvotes: 3