Dynamically embedding Usercontrols in a page: Possible??

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

Hi, I am wanting to know if it is possible to embed a UserControl into a
Page at runtime.

What I am trying to do is allow a user to specify that they want a "contact
form" or a "latest news" in their page by simply entering {contact form} or
{latest news} in the HTML of their page.

What I have is two asp.net user controls called ContactForm.ascx and
LatestNews.ascx

When retrieving the HTML code from the database, I simply want to replace
{contact from} with a ContactForm.ascx etc

I thought that I could simply create a placeholder and then add the relevant
user control to the placeholder at runtime..

e.g.
// Create a new instance of the contact form user control
MyUserControl.ContactForm contactForm = new MyUserControl.ContactForm();
// Add the newly instantiated contact form to a placeholder in the parent
page
PlaceHolder1.Controls.Add(_user);

When I do the above I receive the following error

Object reference not set to an instance of an object.
private void InitializeComponent()
Line 52: {
Line 53: this.Button1.Click += new
System.EventHandler(this.Button1_Click);
Line 54: this.Load += new System.EventHandler(this.Page_Load);
Line 55:

I assume that the application is trying to bind the click event handler to a
button on my contact form user control but it has not been created yet..

Any advice how to fix this welcomed, or perhaps someone knows of a better
way to do things??

Cheers
Mark
 
Yep, check out the LoadControl API. You pass the relative path to the ASCX
file and it instantiates the control. You then would have to add it into
the page whereever you want it (via Controls.Add).

You mention some problems, and most typically arise because the dynamic controls
aren't recreated upon postback. If you are adding controls dynamically, then
you'll have to remember across postbacks what controls were added where.

-Brock
DevelopMentor
http://staff.develop.com/ballen
 
Hi Brock, thanks, that worked a treat
Cheers
Mark
Brock Allen said:
Yep, check out the LoadControl API. You pass the relative path to the ASCX
file and it instantiates the control. You then would have to add it into
the page whereever you want it (via Controls.Add).

You mention some problems, and most typically arise because the dynamic controls
aren't recreated upon postback. If you are adding controls dynamically, then
you'll have to remember across postbacks what controls were added where.

-Brock
DevelopMentor
http://staff.develop.com/ballen
 

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

Back
Top