Wednesday, August 31, 2011

Load user control dynamically with parameters

This method can be used to load a user control dynamically in ASP.NET and pass parameters in the user control's constructor.

/// 
/// 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

2 comments:

  1. I think I used a method like this in one of last year's assignments. It's a very powerful tool.

    ReplyDelete
  2. @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