Hi,
I'm wondering if it's possible to instantiate an ASP.NET control by name at runtime and have the ASP.NET system look for the .ascx file and compile it into an assembly if necessary?
To clarify, I want to write a function that will take a string that is the name of a control and return an instance of that control without having to compile that control into an assembly in advance. I also want it to get the lastest version of the control
automatically if the .ascx file is updated on disk. Is anything like this possible?
-
-
Yep, it's possible:
Control userControl = LoadControl("~/path/to/usercontrol.ascx"); -
Thanks Sven!
-
Heres a better way:
ASP.usercontrols_basicpanel_ascx myControl = new ASP.usercontrols_basicpanel_ascx();
Where user control is located:
~/usercontrols/basicpanel.ascx -
odujosh wrote:Heres a better way:
ASP.usercontrols_basicpanel_ascx myControl = new ASP.usercontrols_basicpanel_ascx();
Where user control is located:
~/usercontrols/basicpanel.ascx
Doesn't work. You're only instantiating the code behind class that way, the .ascx part of the control doesn't get compiled. -
Sven Groot said:odujosh wrote:Heres a better way:
ASP.usercontrols_basicpanel_ascx myControl = new ASP.usercontrols_basicpanel_ascx();
Where user control is located:
~/usercontrols/basicpanel.ascx
Doesn't work. You're only instantiating the code behind class that way, the .ascx part of the control doesn't get compiled.Hmm - works for me just fine Sven.
I add the instantiated control to an area on the page, for example:
ASP.controls_matrixcell_ascx matrixCell = new ASP.controls_matrixcell_ascx();
Panel1.Controls.Add(matrixCell);great solution odujosh!
-
Disco Patrick said:Sven Groot said:*snip*
Hmm - works for me just fine Sven.
I add the instantiated control to an area on the page, for example:
ASP.controls_matrixcell_ascx matrixCell = new ASP.controls_matrixcell_ascx();
Panel1.Controls.Add(matrixCell);great solution odujosh!
This is an old thread, but...
I think odujosh's method works with a Web Application Project, or a precompiled web site. It does not work however work with the VS2005 Web Site model.
I think, anyway, my memory's a bit foggy on this.

-
Sven Groot said:Disco Patrick said:*snip*
This is an old thread, but...
I think odujosh's method works with a Web Application Project, or a precompiled web site. It does not work however work with the VS2005 Web Site model.
I think, anyway, my memory's a bit foggy on this.

Actually, I'm using the Web Site model.
EDITED TO ADD:
While you can instantiate your user control from a page's code-behind file using the ASP.controls_controlname_ascx way, you cannot do this from an ordinary c# class, as the ASP namespace is not available there.
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.