Friday, December 31, 2010

Load Usercontrol Dynamically in WebForm by Dynamically invoking any Constructor of the user control

We can Programmatically load a UserControl to a WebForm using the following code.

Add a place holder(eg:MyPlaceHolder) control to .aspx page

Write the follwing code to Code-Behind File(.aspx.cs)

UserControl MyUserControl  = Page.LoadControl("UserControl1.ascx") as UserControl;
MyPlaceHolder.Controls.Add(accordionUserControl);

The problem with above approach is LoadControl() function returns instance of UserControl by calling Default Constructor of the UserControl.When we have more  than one Constructor. We cannot use LoadControl() function. Below is the solution to this problem.

create a new function called LoadUserControl() function. This function accepts two parameters.

1. Url to UserControl
2. Params Object[]
3.Returns instance of UserControl

The params keyword lets you specify a method parameter that takes an argument where the number of arguments is variable.

Code:

protected UserControl LoadUserControl(string UserControlPath, params object[] constructorParameters)
{

List constParamTypes = new List();

//Get the Type of Params passed and save it ti List
foreach (object constParam in constructorParameters)
{
constParamTypes.Add(constParam.GetType());
}

//Load user control using the url supplied
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 UserControl
return ctl;
}
 

Now use the following code in Code-Behind File to load UserControl Dynamically using Any Constructors

UserControl MyUserControl = LoadUserControl("/Reservation/Accordion.ascx", url, lstItem,cssEnabled, pnl);
MyPlaceHolder.Controls.Add(accordionUserControl);

1 comment: