///
/// This method loads a web user control with parameters
///
/// The path of the usercontrol eg: 'Popup.ascx' /// Any parameters which the user control expects /// Current page ///
public static UserControl LoadControl(string UserControlPath, Page page, params object[] constructorParameters)
{
UserControl ctl = null;
try
{
List constParamTypes = new List();
foreach (object constParam in constructorParameters)
{
constParamTypes.Add(constParam.GetType());
}
ctl = page.LoadControl(UserControlPath) as UserControl;
// Find the relevant constructor
System.Reflection.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);
}
}
catch (Exception ex)
{
//Exception Handling
}
// Finally return the fully initialized UC
return ctl;
}
For more details visit this blog entry
I think I used a method like this in one of last year's assignments. It's a very powerful tool.
ReplyDelete@4thguy You'll be using it a lot more once you start working on ASP.NET.. Actually I don't know why the .NET team hasn't incorporated something like this in the framework ages ago (if they have, I don't know about it!)
ReplyDelete