Friday, October 9, 2009

How to pass parameters to UserControl

  1. Define a constructor method in your UserControl class
    public partial class MyUserControl : System.Web.UI.UserControl
    {
        public MyUserControl()
        {
        }
        public MyUserControl(string param1, int param2, bool param3)
        {
            // Do anything you whant for your parameters here
            textbox1.Text = param1;
            .....

        }
    }
  2. Define our customize LoadControl() method so that the parameters can be pass into the UserControl
    private UserControl LoadUserControl(string controlPath, params object[] parameters)
    {
        List<Type> paramTypes = new List<Type>();
        foreach(object param in parameters)
        {
            paramTypes.Add(param.GetType());
        }
        Page page = new Page();
        UserControl uc = page.LoadControl(controlPath) as UserControl;
        ConstructorInfo ci = uc.GetType().BaseType.GetConstructor(paramTypes.ToArray());
        if(ci == null)
        {
            throw new MemberAccessException(
                "The requested constructor was not found on : "
               
    + uc.GetType().BaseType.ToString());
        }
        else
        {
            ci.Invoke(uc, parameters);
        }
        return uc;
    }
  3. Now you can use the LoadControl as below to pass the parameters to the UserControl
    // Initiallize the UserControl with it parameters .....UserControl myControl = LoadControl(
                                        "MyUserControl.ascx"
                                      , "This is value of param1"
                                      ,  1234, true);