User control's elements not getting initialised when added dynamically?

878 Views Asked by At

I've got a custom ASP.Net web user control I've built; done this enough times before but this one is misbehaving and I can't spot why.

Where the calling page includes the user control directly in its markup, all is well and the control behaves as expected.

However if the page adds this particular control dynamically (to a placeholder in the master page, which is what's calling this whole thing) the elements within it stay firmly NULL - nothing from the user control gets written to the client at all, including static content within the user control.

Where might I be going wrong?

4

There are 4 best solutions below

0
On BEST ANSWER

Answer sorted - IDs are insignificant, it can do without, but if you do

Control a = new Control;

it doesn't work whereas

Control a = (Control)Page.LoadControl("~/Folder/Control.ascx");

does work which is what I'd forgotten late at night :-)

0
On

When you are dynamically loading a user control...

For ASP.NET Web Site Project, the following works

Control a = new Control;

For ASP.NET Web Application Project, the following works

Control a = (Control)Page.LoadControl("~/Folder/Control.ascx");
1
On

When you add user control dynamicly you have to generate uniqe ID for each added control.

For example:

Control selWebControl = (Control)Page.LoadControl("~/DL/Templates/FileLibrary.ascx");
selWebControl.ID = "UC" + "_" + dfRow.ID;
0
On

Make sure you are adding it to a Controls collection that is on the page and make sure you are doing it at the right time in the Page LifeCycle. I like to override CreateChildControls.

So make sure you are doing Page.Controls.Add(myNewControl) or PlaceHolder1.Controls.Add(myNewControl).

Might help if you showed the code in which you are dynamically creating the control and adding it to the page