In the preceding section, you used HtmlTextWriter within the Render method to output content. HtmlTextWriter was designed to make it easier to output formatted content that contains HTML.
When you use HtmlTextWriter , the text that you output is automatically indented. So, if you render multiple nested HTML tags, HtmlTextWriter indents each nested HTML tag correctly.
HtmlTextWriter also includes several properties and methods that make it easier to output HTML content. The following is a partial list of the methods of HtmlTextWriter :
In the preceding section, you created a control that displays the text "Hello World!" . Suppose that you want to modify the control so that it displays the text with a green font. To do so, you could update the Render method like this:
Protected Overrides Sub Render( objTextWriter As HtmlTextWriter ) Dim strText As String strText = "<font color=""green"">Hello World!</font>" objTextWriter.Write( strText ) End Sub
Here, you add an HTML <font> tag with its color attribute set to the value green . Writing HTML in this manner can get messy. Notice that you must double up the quotation marks to get them to display correctly within a Visual Basic string. If the tag had multiple attributes, the situation would only be worse .
Instead of writing the HTML tags yourself, you can have HtmlTextWriter do it for you. Here's how you could rewrite the Render method, taking full advantage of the methods of HtmlTextWriter :
Protected Overrides Sub Render( objTextWriter As HtmlTextWriter ) objTextWriter.AddAttribute( "color", "green" ) objTextWriter.RenderBeginTag( "font" ) objTextWriter.Write( "Hello World!" ) objTextWriter.RenderEndTag() End Sub
When the Render method is called, the following text is output:
<font color="green">Hello World!</font>
By taking advantage of the methods of the HtmlTextWriter class, you can write code that is easier to read and maintain.
When using the methods of HtmlTextWriter , you also have the option of using the HtmlTextWriterTag , HtmlTextWriterAttribute , and HtmlTextWriterStyle enumerations. These enumerations contain lists of standard HTML tags, attributes, and style attributes.