How To Render An ASP.NET Control To A String

A simple code snippet. I like to use “using” statements to make sure the various resources get cleaned up in a timely fashion.

Here it is:

var newContent = string.Empty;

using (var stringWriter = new StringWriter())
using (var htmlWriter = new HtmlTextWriter(stringWriter))
{
    foreach (var control in controls)
    {
        control.RenderControl(htmlWriter);
    }

    newContent = stringWriter.ToString();
}

return newContent;
blog comments powered by Disqus