.Net Development - Dynamically adding user controls

gweidner
gweidner used Ask the Experts™
on
Can anybody help me with a sample for adding user controls dynamically in ASP.Net / C# (Visual Stuido 2005).  I am making use of RAD Controls (Telerek controls) to build a user friendly query / search page.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
create a placeholder control on the page where you want to add the controls, then:

PlaceHolderObj.Controls.Add(new ControlType(Arguments));

Commented:
For User Controls (e.g. the controls which end with a .ascx extension) you would use:

Control c = Page.LoadControl("yourfile.ascx")
PlaceHolderObj.Controls.Add(c);

Please note that if the control is cached you would need some additional code if you want to initialize the control.


Control c = Page.LoadControl("yourfile.ascx")
PlaceHolderObj.Controls.Add(c);


Control bc;
bool isCachable = false;

PartialCachingControl pcc = null;
if(c.GetType()==typeof(PartialCachingControl))
{
      isCachable = true;
      pcc = (PartialCachingControl)c;
}
bc = (pcc==null?c:pcc.CachedControl);

if(!isCachable || (isCachable && bc!=null))
{
      // initialize the control
      bc.InitializeCodeWhatEverYouNeed()
}


Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial