dynamic creation of user controls

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
 
H

Hans Kesting

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
 
A

Adie

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

Kevin Spencer

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top