Dynamically Render A Web User Control

I recently ran into a situation where I wanted to render the contents of a user control either directly to the current HTML stream or to a file format like MS Word. Fortunately .NET has the 'LoadControl' function that takes the virtual path of a User Control and returns a Control object. In order to get the rendered output of a user control into an HTML32TextWriter, you can use the following code:

Control report;
A0
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
Html32TextWriter hw = new Html32TextWriter(sw);
A0
report = LoadControl("WebUserControl.ascx");
report.RenderControl(hw);

One word of caution: When loading a Web User Control through the LoadControl() method, the normal page lifecycle events, such as Page_Init and Page_Load, are not called. To make up for this deficiency, you can cast the returned Control object to the User Control type and call any required methods directly from the object reference before rendering the control. For example, I created an IReportUserControl interface that defines a LoadReport() method, and which all report-type Web User Controls derive from. Then I can simply insert the following code in order to run the proper initialization logic:

report = LoadControl("WebUserControl.ascx"); 
A0
((IReportUserControl)report).LoadReport(); //Initialize the control 
A0
report.RenderControl(hw);

24 Comments

  • Nice tip, Scott.

    This is something that I'll use really soon.

    Thanks!
    Eduardo Costa.

  • You can do something like this before calling RenderControl:

    Page page = new Page();
    page.Controls.Add(report);

    In this case Init method will be called.

  • Can you give more detail on your IReportUserControl interface and LoadReport function please.

  • @Peter,
    Basically the IReportUserControl interface is just a simple interface with one method: void LoadReport(StringDictionary parameters);. You can choose how to represent your parameters, but in my case a key/value stringDictionary worked best.
    Once the interface is defined, your ASCX user control should implement it, like so:
    public partial class Review_BiographicalReport : System.Web.UI.UserControl, IReportUserControl

    Then the LoadReport function can do any data binding or calculations required. After that you just load the user control, cast it as an IReportUserControl and call the LoadReport function, so in the above code.

  • hi, whenever i try to use this code i get error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    where GridView1 is a gridview control used in .ascx file.
    Help Please

  • hi,
    i'm new to this site and to asp.net too.
    i'm having a problem.
    I,ve a user cntrol which is displaing a single row of a table in a label control.
    Now, i need to render that user control on an aspx page, say n times (depending upon the no. of rows in the table), but dont know how to achive it. any suggestion??
    thnx in advance.

  • Nice Scott. I've just recently done something very similar. Although instead of interfaces I used inheritance. I created a control that inherited UserControl and override RenderControl. With this I simply called OnInit, OnLoad and OnRender before calling base.RenderControl. Any control that inherits this can now render the contents to string and still have its lifecycle events executed. You need to make sure you check they have'nt already fired first though otherwise inclduing them in the control tree will cause duplicate calls.

  • Hi Scott, I am having same situation. But here I have a button control in my control and its click event. So, how can I get my button's click event in my main page?

  • What about fetching the user control path through view state, using Page.LoadControl() method and render it dynamically?

  • I created public properties on the user control and access them using reflection. I also had methods on the user control invoked through reflection same way.

    Now, question... how would you render a user control if it has encoded html (useing Html32TextWriter removes the encoding) Anyone?

  • Just read was all of the cutest wow power leveling initially and so i became a great many flatters for them. Still, following with regards to a calendar month possibly even longer, the part of all of the wow power leveling on top of the key begun mucking about alone and so i wasn't able to buy it to last upright vacuum cleaner. I choose technique they appear when they are not necessarily thrown, so I prevented giving him or her as much once this kind of begun proceeding. They even now looked good with denim jeans whilst, they looked sort of amusing about this denim jeans mainly because the flap regarding wow power leveling was just draping about and then looked sort of strange. Now, There's no doubt that the theory is that all of the key was initially a delightful understanding, they only absolutely modified pattern after having a couple brings that i'm not sure whether it's correctable.

  • I haven¡¦t checked in here for some time because I thought it was getting boring, but the last few posts are good quality so I guess I will add you back to my daily bloglist. You deserve it my friend :)

  • I am really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you modify it yourself? Either way keep up the excellent quality writing, it's rare to see a nice blog like this one these days..

  • Nice being visiting your blog again, it has been months to me. Well this article in which I’ve been waited for way too long. Great webpage brother I am gona inform this to every one my friends and contact lenses. The information you discussed through your post is actually functional. I admire your work. Wish you all the luck for the blogging efforts.

  • Measuring Your Level of Competency at Your Job

  • Really no matter if someone doesn't be aware of afterward its up to other people that they will assist, so here it takes place.

  • Hopkins is the taller of the two guys, wearing sunglasses, 21 hour stubble. No idea who the short dude is, but he's part of what is now the outing of Erin Andrews and Cougar Town actor Josh Hopkins as a new couple. Good for EA.

  • The company with its strong presence in over 42 countries worldwide has made a niche of itself by transforming the simplest Jute Bags and Organic cotton bags into a revolution in the Western world..

  • Good write-up, I'm regular visitor of one's website, maintain up the nice operate, and It's going to be a regular visitor for a lengthy time.

  • Thus the whole fabric, and especially Chichikov, came crashing to the ground.

  • Five weeks after starting my job the firm I was working for went bankrupt. I had not even received my first paycheck! After a couple of months it was looking like an impossible task to find a new job. I wanted to stay because of my girlfriend, but it was starting to look like I would have to return to England as I had nearly spent all my money.

  • Yelp prevents businesses that are sub-par from continuing that way.

  • watches Fifth of days, they be used during his iwc watches since son of railroad known worldwide for.

  • Dynamically Render A Web User Control - Scott's Blog gmncdn borse burberry

Comments have been disabled for this content.