views:

22

answers:

1

How can I create an instance of a web control at runtime using reflection? I created a series of controls that implement a common interface and I would like to create these controls based on the name of the control which is stored in my database.

I have attempted (and failed) to create an instance of these controls using Activator.CreateInstance in the following ways:

Activator.CreateInstance("MyUserControl")

and

Activator.CreateInstance("ASP","controls_myusercontrol_ascx")

...and both return null.

I've also attempted to simply get the type of the control by trying..

Type t = Type.GetType("controls_myusercontrol_ascx");

and

Type t = Type.GetType("MyUserControl");

...and it returns null.

If I explicitly declare an object as controls_myusercontrol_ascx or MyUserControl, there is no issue -- but it can't be found with reflection.

Is it possible to create web user controls using reflection at run time? If so, how can I?

+1  A: 

You can do this with the LoadControl method on the Page or Control class. From the Visual Studio help:

void Page_Init(object sender, System.EventArgs e)
{
    // Instantiate the UserControl object
    MyControl myControl1 =
        (MyControl)LoadControl("TempControl_Samples1.ascx.cs");
    PlaceHolder1.Controls.Add(myControl1);
}
Carl Raymond