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

3 comments:

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

    ReplyDelete
    Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from .Net Core Training in Chennai. or learn thru .Net Core Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
      or Es6 Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

      Delete
  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