Saturday, February 19, 2011

StringWriter and HTMLTextWriter objects to emit HTML in custom Webparts

You could also use StringWriter and HTMLTextWriter objects to write HTML to the Web part rather than the LiteralControl.

For example, the following code creates a simple StringBuilder object, then writes that through using the
StringWriter and HtmlTextWriter objects:

StringBuilder sb = new StringBuilder();
sb.AppendLine(“<table border=’0’><tr><td>”);
StringWriter spStrWriter = new StringWriter(sb);
HtmlTextWriter htmlTxtWriter = new HtmlTextWriter(spStrWriter);
Page.RenderControl(htmlTxtWriter);

Admittedly, the use of multiple literalcontrol objects is not the most elegant of ways to emit HTML
when rendering Web parts. See an example usage of Literal Controls mentioned below:

StringBuilder sb = new StringBuilder();
sb.AppendLine(“<table border=’0’><tr><td>”);
this.Controls.Add(new LiteralControl(sb.ToString()));

ASP.NET provides a rich framework for writing HTML out to the page, which includes the HtmlTextWriter class. We can leverage this while writing custom webparts