views:

125

answers:

2

I have a webpage in ASP.NET 3.5 that will be creating WebControls dynamically. The WebControls that it will be creating will be known by their fully qualified path (ie - System.Web.UI.WebControls.whatever). The reason for this is because I am allowing the user to decide what controls will go on the webpage. Of course, there's more complexity than this, but that is it in a nutshell.

Simply put - how do I create a WebControl on a webpage by it's fully qualified path?

I realize that the answer will probably end up using reflection, but I have little experience using reflection and I don't want to shoot myself in the foot by making a newbie mistake.

+1  A: 

object widget = Activator.CreateInstance ( Assembly.GetType ( name ) );

where name is the string of the fully qualified type

JDMX
The only thing to remember is that the `Activator` only works with public classes that implements a default constructor, that is, a parameterless constructor.
Paulo Santos
I think this is close, but not quite there yet. Assembly has no static method of GetType(), but an instance of Assembly does, of course.
Jagd
you can also do typeof( x ) to get the type needed for Activator.CreateInstance. x then equals System.Web.UI.WebControls.Label, System.Web.UI.WebControls.Textbox, or any other type you want to dynamically create
JDMX
+2  A: 

try to call this way: Activator.CreateInstance(Type.GetType("TypeName"));

where TypeName is fully qualified name, including assembly. in my case it looked this way:

Activator.CreateInstance(Type.GetType("System.Web.UI.WebControls.Label, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"));

to be sure about full name in your case, try to output typeof(System.Web.UI.WebControls.Label).FullName and use it as a pattern

Andrey
The only thing to remember is that the `Activator` only works with public classes that implements a default constructor, that is, a parameterless constructor.
Paulo Santos
i disagree. It can instantiate private classes if you manage to dig out Type object from Assembly object. about parameterless contructor also not true, you can pass parameters to constructor as second parameter to CreateInstance
Andrey
This works. Thank you!
Jagd