Adding User Controls in your ASP.NET Page

ASP.Net provides many ways to re-use the code. This not only save time but also keeps your code in very organised way. When I say re-use the code, this means not only server end programming code, but also HTML content. These User Control work in the same way as ASPX Page, except it have extension ASCX. User Controls can be added in ASP.NET Page in both ways i.e. static and dynamically. Let's discuss them.

First Method : Adding User Control in Design Mode
1. Open the page in Design Mode in Visual Studio IDE
2. Open the Solution Explorer and locate the required User Control
3. Drag the User Control on required Placeholder
4. As you drag and drop the User Control on page, IDE automatically adds the reference of User Control in HTML for you.
5. You can view your custom properties in User Control's properties tab.

Second Method : Adding User Control in HTML
1. Register your User Control in Page
<%@ Register Src="UserControls/footer.ascx" TagName="Footer" TagPrefix="uc1" %> 2. Declare or call the User Control in the place where it needs to be displayed.
<uc1:Footer ID="footer" runat="server" /> 3. Pass the properties value along with declaration of User Control
<uc1:Menu ID="Menu1" runat="server" ActiveMenu="HOME" />

Third Method : Adding User Control dynamically (Without constructor)
Adding User control dynamically is very easy. Just need to call Loadcontrol method provided by asp.net. It takes the control path as parameter to load. placeholder.Controls.Add(LoadControl("~/controls/Controlname.ascx"))

Forth Method : Adding User Control dynamically (With constructor)
ASP.Net Loadcontrol method doesn't allow constructors to load the control. So how do we load the control with constructors? Below is overload method of Loadcontrol. Using the below method we can load the controls with constructors. '------ Loading User Control with the constructors ---------
    Public Overloads Function LoadControl(ByRef pg As Page, ByVal UserControlPath As String, _
ByVal ParamArray constructorParameters As Object()) As UserControl

        Dim constParamTypes As New Generic.List(Of Type)
        For Each constParam As Object In constructorParameters

        Dim ctl As UserControl = TryCast(pg.LoadControl(UserControlPath), UserControl)

        ' Find the relevant constructor
        Dim constructor As Reflection.ConstructorInfo = ctl.[GetType]().BaseType.GetConstructor(constParamTypes.ToArray())

        'And then call the relevant constructor
        If constructor Is Nothing Then
            Throw New MemberAccessException("The requested constructor was not found on : " + ctl.[GetType]().BaseType.ToString())
            constructor.Invoke(ctl, constructorParameters)
        End If

        ' Finally return the fully initialized UC
        Return ctl
    End Function

LoadControl(me.page,"~/controls/Controlname.ascx", "constructor value")

Hope, it may be useful.


Blogs | About Me | My Projects | Contact Me