A personal repository of technical notes. - CSC

How to Convert an ASP.NET Control to String

Problem
Need to generate an HTML string from an ASP.NET web control created in code-behind without rendering it on the web page.

Solution
Use the control's RenderControl() method with a StringWriter to generate the HTML.
  

// Code sample of a utility method to convert a control to an HTML string

public static string RenderControlToString(Control control)

{

string renderedControl = null;

if (control != null)

{

using (StringWriter tempStringWriter = new StringWriter())

{

using (HtmlTextWriter tempHtmlTextWriter = new HtmlTextWriter(tempStringWriter))

{

control.RenderControl(tempHtmlTextWriter);

renderedControl = tempStringWriter.ToString();

tempHtmlTextWriter.Close();

}

tempStringWriter.Close();

}

}

return renderedControl;

}

// Test Utility Method

private void TestRenderControlToString()

{

HyperLink testHyperLink = new HyperLink();

testHyperLink.NavigateUrl = "/MyWebFolder/Default.aspx";

testHyperLink.Text = "Hyper Link Value";

testHyperLink.Target = "_blank";

string renderedControl = Utility.RenderControlToString(testHyperLink);

Response.Write(Server.HtmlEncode(renderedControl));

Response.Write(renderedControl);

}


References
"Control.RenderControl Method (System.Web.UI)." MSDN: Microsoft Development, MSDN Subscriptions, Resources, and More. 27 Mar. 2009
http://msdn.microsoft.com/en-us/library/system.web.ui.control.rendercontrol(VS.80).aspx.

"StringWriter Class (System.IO)." MSDN: Microsoft Development, MSDN Subscriptions, Resources, and More. 27 Mar. 2009
http://msdn.microsoft.com/en-us/library/system.io.stringwriter(VS.80).aspx.

No comments:

Post a Comment