Click here to Skip to main content
15,881,248 members
Articles / Web Development / HTML

Dynamic Loading of ASP.NET User Controls

Rate me:
Please Sign up or sign in to vote.
3.87/5 (35 votes)
4 Jun 2010CPOL3 min read 368.2K   9.8K   63  
Demonstrates how to dynamically add User Controls to pages at runtime using the LoadControl method

Partial Class _Default
    Inherits System.Web.UI.Page

    ' Declare 2 variable to handle user control after postback
    Dim controlID As String = "MyUserControl"
    Dim Shared createAgain As Boolean = False


    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' Create instance of the UserControl SimpleControl
        Dim ucSimpleControl As usercontrol_SimpleControl = LoadControl("~/usercontrol/SimpleControl.ascx")

        ' Set the Public Properties
        ucSimpleControl.FirstName.Text = "Milind"
        ucSimpleControl.LastName.Text = "Chavan"

        ' Create Event Handler for btnPost Click 
        AddHandler ucSimpleControl.btnPostClk, AddressOf ucSimpleControl_onPostClk

        ' Add the SimpleControl to Placeholder
        Placeholder1.Controls.Add(ucSimpleControl)

        ' Add the instance of the SimpleControl to Session Variable
        Session.Add((Session.Count + 1).ToString(), ucSimpleControl)

        ' Set createAgain = true
        createAgain = True
    End Sub

    Protected Sub ucSimpleControl_onPostClk(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim ucSimpleControl As usercontrol_SimpleControl = DirectCast(DirectCast(sender, System.Web.UI.WebControls.Button).Parent, usercontrol_SimpleControl)
        lblUser.Text = ("Welcome " + ucSimpleControl.FirstName.Text & " ") + ucSimpleControl.LastName.Text

    End Sub

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ctrl As Control = GetPostBackControl(Me.Page)

        ' Check if the postback is caused by the button 
        ' Titled "Click to Create a Dynamic Control"
        ' OR
        ' createAgain field is true 
        ' which means a call is made to the server while the 
        ' user control is active  

        If (ctrl IsNot Nothing AndAlso ctrl.ClientID = Button1.ClientID) OrElse createAgain Then
            'should be set before the CreateUserControl method
            createAgain = True

            CreateUserControl(controlID)
        End If

        ' Check if the postback is caused by the button 
        ' Titled "Click to Create a Dynamic Control"
        ' OR
        ' createAgain field is true 
        ' which means a call is made to the server while the 
        ' user control is active  

        If (ctrl IsNot Nothing AndAlso ctrl.ClientID = Button1.ClientID) OrElse createAgain Then
            'should be set before the CreateUserControl method
            createAgain = True

            CreateUserControl(controlID)
        End If


    End Sub

    Protected Function GetPostBackControl(ByVal pg As Page) As Control
        Dim ctl1 As Control = Nothing

        Try
            Dim ctrlName As String = pg.Request.Params.Get("__EVENTTARGET")

            If ctrlName IsNot Nothing AndAlso ctrlName <> [String].Empty Then
                ctl1 = Page.FindControl(ctrlName)
            Else
                Dim cph As ContentPlaceHolder = DirectCast(Page.FindControl("Main"), ContentPlaceHolder)
                Dim i As Integer = 0, len As Integer = Page.Request.Form.Count
                While i < len
                    Dim ctl As String() = Page.Request.Form.AllKeys(i).Split("$"c)
                    If ctl.Length > 2 Then
                        ctl1 = TryCast(cph.FindControl(ctl(2)), System.Web.UI.WebControls.Button)
                    End If

                    If ctl1 IsNot Nothing Then
                        Exit While
                    End If
                    i += 1
                End While
            End If

        Catch ex As Exception
            Throw ex
        End Try

        Return ctl1
    End Function


    Protected Sub CreateUserControl(ByVal controlID As String)
        ' createAgain field is set to true in the OnPreInit method
        ' when the 'Create User Control' button is clicked 

        ' the createAgain field is used to check if the
        ' user control is on the page before the call 
        ' if so create the control again and add it to the
        ' Control Hierarchy again
        Try
            If createAgain AndAlso Placeholder1 IsNot Nothing Then
                If Session.Count > 0 Then
                    Placeholder1.Controls.Clear()
                    For i As Integer = 0 To Session.Count - 1
                        Select Case Session(i).ToString()
                            Case "ASP.usercontrol_simplecontrol_ascx"
                                If True Then
                                    ' Create instance of the UserControl SimpleControl
                                    Dim ucSimpleControl As usercontrol_SimpleControl = TryCast(LoadControl("~/usercontrol/SimpleControl.ascx"), usercontrol_SimpleControl)

                                    ' Set the Public Properties
                                    ucSimpleControl.FirstName.Text = DirectCast(Session(i), usercontrol_SimpleControl).FirstName.Text
                                    ucSimpleControl.LastName.Text = DirectCast(Session(i), usercontrol_SimpleControl).LastName.Text

                                    'Create Event Handler for btnPost Click 
                                    AddHandler ucSimpleControl.btnPostClk, AddressOf ucSimpleControl_onPostClk

                                    'Add the SimpleControl to Placeholder
                                    Placeholder1.Controls.Add(ucSimpleControl)
                                    Exit Select
                                End If
                        End Select
                    Next
                End If
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

End Class

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions