posts - 236, comments - 445, trackbacks - 56

My Links

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

Archives

Free Programming Language Training

A Good Example of Asp.net LoadControl with multiple parameters

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) ;
}

Print | posted on Thursday, March 23, 2006 2:36 AM |

Feedback

Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

It seems when the UserControl is loaded on to the page; in the Page_Load event of the UC I have if (!Page.IsPostBack) which resolves to false. This is the first time the UC is loaded so anything after if (!Page.IsPostBack) should fire?
7/9/2007 6:42 AM | Mike
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

Instead of sb.Append("
") ;

try sb.Append(Environment.NewLine);
12/19/2007 7:14 AM | scottt732
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

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
4/15/2008 3:41 PM | Daniel
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

Great! Thank you
4/22/2008 7:55 PM | Morteza
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

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>();
6/12/2008 9:54 AM | Jimbo
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

You also need to add the System.Reflection class reference.
7/6/2008 7:37 PM | DDW
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

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 :(
10/15/2008 1:31 AM | jos
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

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)
1/6/2009 10:37 AM | mk
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

You rock. Thank you.
4/8/2009 6:49 AM | DotNetNow
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

Grreat !! thanks a lot.
4/25/2009 5:31 AM | Nwb
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

Thanks you very much! You're No1
4/28/2009 1:40 AM | angmaynho
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

Beautiful post... Life saver my friend!!!! Thanks a lot!
5/29/2009 2:57 AM | Alejandro Morilla
Gravatar

# re: A Good Example of Asp.net LoadControl with multiple parameters

great! thanks man!
9/3/2009 7:24 PM | jl
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: