views:

739

answers:

2

I am building an application where a page will load user controls (x.ascx) dynamically based on query string.

I have a validation summary on the page and want to update it from the User Controls. This will allow me to have multiple controls using one Validation Summary. How can I pass data between controls and pages.

I know I can define the control at design time and use events to do that but these controls are loaded dynamically using Page.LoadControl.

Also, I want to avoid using sessions or querystring.

A: 

Assuming you're talking about asp's validator controls, making them work with the validation summary should be easy: use the same Validation Group. Normally, I derive all usercontrols from a base class that adds a ValidationGroup property whose setter calls a overriden method that changes all internal validators to the same validation group.

The tricky part is making them behave when added dynamically. There are some gotchas you should be aware of, mainly concerning the page cycle and when you add them to your Page object. If you know all the possible user controls you'll use during design time, I'd try to add them statically using EnableViewState and Visible to minimize overhead, even if there are too many of them.

Jorge Alves
+1  A: 

Found a way of doing this:

Step 1: Create a Base User Control and define Delegates and Events in this control.

Step 2: Create a Public function in the base user control to Raise Events defined in Step1.

'SourceCode for Step 1 and Step 2
Public Delegate Sub UpdatePageHeaderHandler(ByVal PageHeading As String)
Public Class CommonUserControl
    Inherits System.Web.UI.UserControl

    Public Event UpdatePageHeaderEvent As UpdatePageHeaderHandler
    Public Sub UpdatePageHeader(ByVal PageHeadinga As String)
     RaiseEvent UpdatePageHeaderEvent(PageHeadinga)
    End Sub
End Class

Step 3: Inherit your Web User Control from the base user control that you created in Step1.

Step 4: From your Web User Control - Call the MyBase.FunctionName that you defined in Step2.

'SourceCode for Step 3 and Step 4
Partial Class DerievedUserControl
    Inherits CommonUserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     MyBase.PageHeader("Test Header")
    End Sub
End Class

Step 5: In your page, Load the control dynamically using Page.LoadControl and Cast the control as the Base user control.

Step 6: Attach Event Handlers with this Control.

'SourceCode for Step 5 and Step 6
Private Sub LoadDynamicControl()
    Try
     'Try to load control
     Dim c As CommonUserControl = CType(LoadControl("/Common/Controls/Test.ascx", CommonUserControl))
     'Attach Event Handlers to the LoadedControl
     AddHandler c.UpdatePageHeaderEvent, AddressOf PageHeaders
     DynamicControlPlaceHolder.Controls.Add(c)
    Catch ex As Exception
     'Log Error
    End Try
End Sub
mjnagpal