dynamic creation of user controls

  • Thread starter Thread starter Adie
  • Start date Start date
A

Adie

Hi, I wonder if anyone can tell me how to add user controls to a page
dynamically?

In context: I have a bunch of HTML tables which due to time
constraints can't be populated to a database, so I was planning on
cutting the HTML source and creating a user control from said source.
I will then populate the relevant database for the product with the
name of the user control, so if someone selects product "blah" the
query returns the name of the relevant control with other details.

How then might I add this code to the page, would I better off using
the old style <% -- inline code here -- %> for example
<uc1:<%=some_control_name%> id=" <%=some_control_name%>"
runat="server"> in the aspx web form or by using code-behind?

And would I have register each control that might be used on the page
too?

<%@ Register TagPrefix="uc1" TagName="cb4Way" Src="pecs/cb4Way.ascx"%>
<%@ Register TagPrefix="uc1" TagName="pecs/tubingNTTPec.ascx"

TIA
 
Adie said:
Hi, I wonder if anyone can tell me how to add user controls to a page
dynamically?

There is a LoadControl method that takes a relative path to an ascx as
parameter.

Use a PlaceHolder control where you want your dynamic controls to appear
( say "PlaceHolder1"), then add your control to it:
PlaceHolder1.Controls.Add(LoadControl(relativeASCXPath));


Hans Kesting
 
Hans said:
There is a LoadControl method that takes a relative path to an ascx as
parameter.

Use a PlaceHolder control where you want your dynamic controls to appear
( say "PlaceHolder1"), then add your control to it:
PlaceHolder1.Controls.Add(LoadControl(relativeASCXPath));

Excellent, thank you Hans.
 
There is a LoadControl method that takes a relative path to an ascx as
parameter.

In addition, if you want to have some control over the User Control after
loading it, the LoadControl() method returns a reference to the Control you
added. Also, note that when you dynamically add any Control to a WebForm,
you must re-add it with each PostBack in order for it to "remain" on the
page across PostBacks.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
Back
Top