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