Dynamically Adding User Controls to Web Page With ASP.NET

I’ve been very busy lately and unfortunately didn’t have enough time to stop here to write about things I have been working on. There are other subjects that I’d like to talk about but, for now, I’ll share my findings with asp.net user controls dynamically added to the page, difficulties, limitations and solutions.

I’m working on a Ajax based web site that basically contains a content area in the right, where I need to put the dynamic content, based on the user selection on the left menu. The ongoing work can be seen here.

The easier way to do this is to create an asp.net UserControl for the content of each page and to dynamically add each control to the page based on the user selection. I also added an UpdateProgress panel for better user experience. However, here is where the problems start. First off, you cannot simply instantiate an asp.net UserControl through its constructor and add it to the page. That won’t work. Instead, you’ll need to use the factory method Page.LoadControl(), providing it the virtual path to your control so that it returns the instance for you. Eg.:

<span class="lnum">   1:  </span>Control c = <span class="kwrd">this</span>.LoadControl(<span class="str">"~/MyUserControl.ascx"</span>);   <span class="rem">// Instantiate the user control</span>

<span class="lnum">   2:  </span><span class="kwrd">this</span>.ContentArea.Controls.Add(c);    // Add it to the placeholder

Here, we’re instantiating the control and adding it to the page. So far, so good. But, what happens if your user control needs to execute some javascript function upon loading? Even if you explicitly put