views:

40

answers:

2

I need to create a .NET control (in ASP.NET) from a string that represents the control's name.

Control myList = SomeSystemClass.GetControlByName("DropDownList");

I guess there is some reflection method in the .NET platform that allows this but I have no idea which one. Any ideas?

+1  A: 

I think you'll need to combine one of the Type.GetType() overloads with Activator.CreateInstance to create a factory method like you describe.

Relevant docs:

Edit It just occurred to me that, if you are able to use the type cast as shown in your code snippet, reflection should be absolutely unnecessary. If you have the ability to declare a variable as a DropDownList, then it is by far easier to simply include = new DropDownList(); and call it good.

Edit 2 There was, for a moment, a post that may have correctly intuited your intent. If you are looking for a control that already exists, and you have a handle on its naming container (which may be the page, or may be a data-bound control) then you can retrieve the control with the FindControl method, then cast to the relevant type.

Relevant docs: http://msdn.microsoft.com/en-us/library/486wc64h.aspx

kbrimington
+1  A: 

For Server Controls:

Control c = Page.ParseControl("<asp:DropDownList runat='server' />");

Or more specifically for your example:

string ctrlName = "DropDownList";
Control c = Page.ParseControl("<asp:" + ctrlName  + " runat='server' />");

For User Controls:

MyControl myControl1 = (MyControl)LoadControl("TempControl_Samples1.ascx");
Patricker