Posted By: rhm | Mar 9th, 2007 @ 4:09 AM
page 1 of 1
Comments: 7 | Views: 7641
rhm
rhm
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?


Sven Groot
Sven Groot
My name has 9 letters. Coincidence? I think not...
Yep, it's possible:

Control userControl = LoadControl("~/path/to/usercontrol.ascx");
odujosh
odujosh
Need Microsoft SUX now!
Heres a better way:

ASP.usercontrols_basicpanel_ascx myControl = new ASP.usercontrols_basicpanel_ascx();

Where user control is located:
~/usercontrols/basicpanel.ascx
Sven Groot
Sven Groot
My name has 9 letters. Coincidence? I think not...
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!

Sven Groot
Sven Groot
My name has 9 letters. Coincidence? I think not...

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. Smiley

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.

page 1 of 1
Comments: 7 | Views: 7641
Microsoft Communities