Thursday, February 18, 2010

Aspx Load User Control with Params

private UserControl LoadControl(string UserControlPath, params object[] constructorParameters)
{
// add this to aspx page that needs to load a .ascx control
// http://www.effegidev.com/post/WebUserControls-and-Parameters.aspx
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;
}

No comments: