How do I get the HTML output of a UserControl in .NET (C#)?

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.

Here’s a code example for this solution:

string html = String.Empty;
using (TextWriter myTextWriter = new StringWriter(new StringBuilder()))
{
    using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))
    {
        myControl.RenderControl(myWriter);
        html = myTextWriter.ToString();
    }
}

Leave a Comment