Geeks With Blogs

News Awarded Microsoft MVP C#.NET - 2007, 2008 and 2009


I am born in Bangladesh and currently live in Melbourne, Australia. I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net)and born in Bangladesh.
I am founder and Chief Executive Officer of
Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Co-founder and core developer of Pageflakes www.pageflakes.com.
Simplexhub, is on its mission to build a smart virtual community in Bangladesh and recently launched beta realestatebazaar.com.bd an ASP.NET MVC application written in C#.NET.


Some of My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET

Shahed Khan blog

source: http://codebetter.com/blogs/sahil.malik/archive/2006/03/05/139828.aspx

The inability of LoadControl to accept Constructor Parameters is a real pain . This post tells how to get around of it.

With UserControls we are limited to calling something like -

LoadControl("WebUserControl.ascx") ;

Wouldn't it be nice if we could instead do ...

LoadControl("WebUserControl.ascx",constructorparameter1, constructorparameter2, constructorparameter3 ...) ;

So for instance, it would be nice if the following code would work -

Control toAdd = LoadControl("WebUserControl.ascx","Sahil Malik",5) ;
PlaceHolder1.Controls.Add(toAdd) ;

Note: There is a new overload new in .NET 2.0 which takes the signature LoadControl(Type,object[]), which is very similar to the above. But it is frequently problematic in ASP.NET 2.0 to refer to a user control in a strongly typed manner.

1. First of all we write a UserControl.

public partial class WebUserControl : System.Web.UI.UserControl
{
    public WebUserControl()
    {
    }

    public WebUserControl(string labelText, int howManyTimes)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder() ;
        for (int i = 1; i <= howManyTimes; i++)
        {
            sb.Append(labelText) ;
            sb.Append("
") ;
        }
        Label1.Text = sb.ToString() ;
    }
}

This is simply appending the same text over and over again. Note that it is important to explicitly create a default public constructor (i.e. one without parameters).

2. Step #2 we add the following private method to your default.aspx, or add it as a protected method to the base class of all our pages..

private UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
{       
    List constParamTypes = new List() ;
    foreach (object constParam in constructorParameters)
    {
        constParamTypes.Add(constParam.GetType()) ;
    }

    UserControl ctl = Page.LoadControl(UserControlPath) as UserControl;

    // Find the relevant constructor
    ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray()) ;

    //And then call the relevant constructor
    if (constructor == null)
    {
        throw new MemberAccessException("The requested constructor was not found on : " + ctl.GetType().BaseType.ToString()) ;
    }
    else
    {
        constructor.Invoke(ctl,constructorParameters) ;
    }

    // Finally return the fully initialized UC
    return ctl;
}

3. And finally, we have to place the following to the Page_Load (or any other suitable place) of default.aspx -

protected void Page_Load(object sender, EventArgs e)
{
    Control toAdd = LoadControl("WebUserControl.ascx","What a Great Example",5) ;
    PlaceHolder1.Controls.Add(toAdd) ;
}

Posted on Thursday, March 23, 2006 2:36 AM | Back to top


Comments on this post: A Good Example of Asp.net LoadControl with multiple parameters

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
Instead of sb.Append("
") ;

try sb.Append(Environment.NewLine);
Left by scottt732 on Dec 19, 2007 7:14 AM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
Thanks, a great help. I converted this to VB.NET:

Private Overloads Function LoadControl(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
constParamTypes.Add(constParam.[GetType]())
Next

Dim ctl As UserControl = TryCast(Page.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())
Else
constructor.Invoke(ctl, constructorParameters)
End If

' Finally return the fully initialized UC
Return ctl
End Function
Left by Daniel on Apr 15, 2008 3:41 PM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
Great! Thank you
Left by Morteza on Apr 22, 2008 7:55 PM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
For the less experienced, you are going to have to add a reference to the following classes:

using System.Configuration;
using System.Collections.Generic;

Also, I had to change the first line to say

List<Type> constParamTypes = new List<Type>();
Left by Jimbo on Jun 12, 2008 9:54 AM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
You also need to add the System.Reflection class reference.
Left by DDW on Jul 06, 2008 7:37 PM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
how can i call this function with ByRef parameters?
i always get the message "The requested constructor was not found on " then i call with ByRef parameters :(
Left by jos on Oct 15, 2008 1:31 AM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
Nice trick. Learned something. But when i needed it, my problem was to set properties on a loaded control. The .ascx of the loader contained only a PlaceHolder and i could not cast the loaded control to a strong type. This is resolved by adding a <%@Register directive for the loaded control in the .ascx of the loader - even when there was no further reference to the registered control.
Source: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/userctrl/default.aspx


(mk)
Left by mk on Jan 06, 2009 10:37 AM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
You rock. Thank you.
Left by DotNetNow on Apr 08, 2009 6:49 AM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
Grreat !! thanks a lot.
Left by Nwb on Apr 25, 2009 5:31 AM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
Thanks you very much! You're No1
Left by angmaynho on Apr 28, 2009 1:40 AM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
Beautiful post... Life saver my friend!!!! Thanks a lot!
Left by Alejandro Morilla on May 29, 2009 2:57 AM

# re: A Good Example of Asp.net LoadControl with multiple parameters
Requesting Gravatar...
great! thanks man!
Left by jl on Sep 03, 2009 7:24 PM

Your comment:
 (will show your gravatar)
 


Copyright © Shahed Khan | Powered by: GeeksWithBlogs.net | Join free