Thursday 3 June 2010

ASP.NET: Render Control into HTML String

Occasionally there is a need to get string representation of ASP.NET control in other words - render it into string instead of let it be rendered on the page. For example, you may want to grab the HTML rendering of an ASP.NET server control and attach it to an email.

The following method renders control into HTML string.

Namespaces used:


using System.Text;
using System.IO;
using System.Web.UI;

Below is RenderControl method implementation, which receives any control and returns its HTML string representation.

C#

public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);

ctrl.RenderControl(hw);
return sb.ToString();
}

VB.NET

Public Function RenderControl(ByVal ctrl As Control) As String
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
Dim htw As New HtmlTextWriter(sw)

ctrl.RenderControl(htw)

Return sb.ToString()

End Function

There are a few drawbacks to this approach, in that any LinkButtons or other controls which depend on being inside an HTML form will fail unless you include the form in the email body too.

See these two (rather old) posts on 4GuysFromRolla.com by Scott Mitchell:

Part 1
http://www.4guysfromrolla.com/articles/091102-1.aspx

Part 2:
http://www.4guysfromrolla.com/articles/102203-1.aspx

0 comments: