how to add a user control progrmatically?

  • Thread starter Thread starter francois
  • Start date Start date
F

francois

Hi,

I would like to add a USER control (not custom control) programmatically to
my aspx page.
I am using something like the following in my page_load code :

*
Bos.UserControls.HeaderFinance header = new HeaderFinance();
this.Controls.Add(header);
*

The problem is that asp.net controls existing in my user control are not
instanciated and are still 'null', then of course it does not work.

Then is there a way to add a user control to a page programatically? Or at
least dynamically. I want to add different user controls on my page
depending of some runtime parameters.

Best regards,

Francois
 
Use the Page.LoadControl() method to load the User Control at run-time. It
returns a reference to the Control you just loaded:

Dim c As MyUserControl = CType(Page.LoadControl("MyUserControl.ascx"),
MyUserControl)

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
I have done it but now I have the following error :

The Controls collection cannot be modified because the control contains code
blocks (i.e. <% ... %>).

Does that mean that the user controls I add programatically are forbidden to
haveany <% %> tags? Or did I left out something?

Francois
 
Back
Top