views:

2844

answers:

4

If I create a UserControl and add some objects to it, how can I grab the HTML it would render?

ex.

UserControl myControl = new UserControl();
myControl.Controls.Add(new TextBox());

// ...something happens

return strHTMLofControl;

I'd like to just convert a newly built UserControl to a string of HTML.

Answered (below):

Using azamsharp's method worked - here's the code example:

TextWriter myTextWriter = new StringWriter();
HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter);

myControl.RenderControl(myWriter);

return myTextWriter.ToString();

You'll need to be using System.IO (to get the StringWriter class).

+1  A: 

Call it's .RenderControl() method.

Joel Coehoorn
+11  A: 

You can render the control using Control.RenderControl(HtmlTextWriter).

Feed StringWriter to the HtmlTextWriter.

Feed StringBuilder to the StringWriter.

Your generated string will be inside the StringBuilder object.

azamsharp
you could also add the control in a "live" controls collection to avoid random exceptions.
korchev
+2  A: 

override the REnderControl method

protected override void Render(HtmlTextWriter output)
{       
   output.Write("<br>Message from Control : " + Message);       
   output.Write("Showing Custom controls created in reverse" +
                                                    "order");         
   // Render Controls.
   RenderChildren(output);
}

This will give you access to the writer which the HTML will be written to.

You may also want to look into the adaptive control architecture of asp.net adaptive control architecture of asp.net where you can 'shape' the default html output from controls.

Xian
+3  A: 
//render control to string
StringBuilder b = new StringBuilder();
HtmlTextWriter h = new HtmlTextWriter(new StringWriter(b));
this.LoadControl("~/path_to_control.ascx").RenderControl(h);
string controlAsString = b.ToString();
Ben Aston