Monday, November 5, 2007 8:30 PM srkirkland

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;
 
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
Html32TextWriter hw = new Html32TextWriter(sw);
 
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"); 
 
((IReportUserControl)report).LoadReport(); //Initialize the control 
 
report.RenderControl(hw);
Filed under: ,

Comments

# re: Dynamically Render A Web User Control

Tuesday, November 6, 2007 1:14 AM by Eduardo Costa

Nice tip, Scott.

This is something that I'll use really soon.

Thanks!

Eduardo Costa.

# re: Dynamically Render A Web User Control

Tuesday, November 6, 2007 2:07 AM by Dmytro Shteflyuk

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.

# re: Dynamically Render A Web User Control

Wednesday, November 21, 2007 10:23 PM by Peter

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

# re: Dynamically Render A Web User Control

Monday, November 26, 2007 1:18 PM by srkirkland

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

# re: Dynamically Render A Web User Control

Tuesday, March 18, 2008 5:17 PM by Pinal Bhatt

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

# re: Dynamically Render A Web User Control

Friday, June 5, 2009 8:42 AM by shatru

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.

# re: Dynamically Render A Web User Control

Thursday, November 5, 2009 3:25 PM by wullie

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.

# re: Dynamically Render A Web User Control

Wednesday, November 3, 2010 5:50 AM by Shailen

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?

# re: Dynamically Render A Web User Control

Wednesday, March 28, 2012 2:38 AM by Abhijat

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

# re: Dynamically Render A Web User Control

Wednesday, July 4, 2012 8:42 AM by bi2002tec

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?

# re: Dynamically Render A Web User Control

Sunday, April 14, 2013 9:55 AM by wow power leveling

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.

# re: Dynamically Render A Web User Control

Monday, April 22, 2013 6:43 PM by neverwinter power leveling

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 :)

# re: Dynamically Render A Web User Control

Friday, April 26, 2013 12:01 AM by neverwinter power leveling

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

# re: Dynamically Render A Web User Control

Thursday, May 9, 2013 4:15 AM by Audie Norberg

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.

# re: Dynamically Render A Web User Control

Thursday, May 9, 2013 9:45 AM by marc by marc jacobs バッグ

Measuring Your Level of Competency at Your Job

# re: Dynamically Render A Web User Control

Monday, May 13, 2013 3:00 PM by Cahill

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.

# re: Dynamically Render A Web User Control

Monday, May 13, 2013 9:45 PM by mulberry iphone case

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.

# re: Dynamically Render A Web User Control

Monday, May 20, 2013 4:55 AM by Mulberry handbag

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

# re: Dynamically Render A Web User Control

Monday, May 20, 2013 3:00 PM by Tim Jennings

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.

# re: Dynamically Render A Web User Control

Monday, May 20, 2013 5:12 PM by Trent Williams

Wow, incredible weblog format! How lengthy have you been blogging for? you made blogging glance easy. The total glance of your site is magnificent, neatly as} the content material!

# re: Dynamically Render A Web User Control

Thursday, May 23, 2013 3:34 AM by ralph lauren france

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

# re: Dynamically Render A Web User Control

Thursday, May 23, 2013 5:11 AM by Louis Vuitton Taschen Outlet

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.

# re: Dynamically Render A Web User Control

Thursday, May 23, 2013 7:00 AM by isabel marant sneakers

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

# re: Dynamically Render A Web User Control

Friday, May 24, 2013 2:50 AM by mulberry outlet uk

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

# re: Dynamically Render A Web User Control

Monday, May 27, 2013 10:26 AM by borse burberry

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