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