Have you ever run across a situation where it would be nice to render an ASP.NET control as a string? For example, let's say that you had to dynamically generate a control at runtime and then embed it's HTML within a <div>. Fortunately, all ASP.NET controls expose the
RenderControl() method. Don't get too excited just yet, the
RenderControl() method doesn't simply return a string. Instead, the
RenderControl() method takes an
HtmlTextWriter as input and renders the control into it. Not so fast though, we can't just create an
HtmlTextWriter object without first having a
TextWriter object. So it boils down to a couple of steps, but rendering an ASP.NET control as a string can be accomplished in the following way:
public string RenderControlAsString(Control myCtrl)
{
// Create a StringBuilder to generate the string
StringBuilder sb = new StringBuilder();
using (StringWriter sw = new StringWriter(sb))
{
using (
HtmlTextWriter tw =
new HtmlTextWriter(sw))
{
// Render the control
myCtrl.RenderControl(tw);
}
}
// Return the control rendered as a string
return sb.ToString();
}
Thursday, December 18, 2008 9:05 AM