Rendering Controls


Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 19.  ASP.NET Web Programming

Rendering Controls

The WebControl class introduces the Render method. You can override the Render method to perform custom HTML rendering via the System.Web.UI.HtmlTextWriter object passed to the Render method.

HtmlTextWriter allows you to add HTML directly to a Web page through generic and specific methods both designed for this purpose. Render is commonly used by server controls to update their presentation on the client.

The HtmlTextWriter object and the Render method can be used to create dynamic pages that are made up of programmatically derived HTML elements. You can write raw HTML or use methods like HTMLTextWriter.WriteBeginTag and HtmlTextWriter.WriteEndTag to simplify rendering the HTML (and probably reduce the likelihood of HTML syntax errors). Refer to Listing 19.6 for an example of dynamically rendered HTML.

Listing 19.6 Dynamically rendered HTML that adds a header to the code database listing
  1:  Private ReadOnly Property FormattedColumn() As String  2:  Get  3:  If (FSortColumn = "") Then  4:  Return "Unordered List"  5:  Else  6:  Return "Ordered List by " & FSortColumn  7:  End If  8:  End Get  9:  End Property  10:   11:  Protected Overrides Sub Render(_  12:  ByVal writer As System.Web.UI.HtmlTextWriter)  13:   14:  MyBase.Render(writer)  15:  writer.WriteBeginTag("center") : writer.Write(HtmlTextWriter.TagRightChar)  16:   17:  writer.WriteBeginTag("i") : writer.Write(HtmlTextWriter.TagRightChar)  18:  writer.Write(FormattedColumn)  19:  writer.WriteEndTag("i")  20:   21:  writer.WriteEndTag("center")  22:   23:  End Sub 

The listing was added to the CacheDemo.sln from Listing 19.5 to render a title for the DataGrid containing the source code from the code database. Line 14 calls the inherited Render method; otherwise , only the dynamic code will be displayed in the form. Lines 15 and 21 write the begin and end tags for centering text, respectively.


Some tags require additional parameter information. For this reason, the right tag character is not rendered on the begin tag. You have to invoke the HtmlTextWriter.TagRightChar to render the right tag character for beginning tags explicitly. This is demonstrated on lines 15 and 17.

Inside the center tag is the italics tag (<i></i>). The result is HTML that centers and italicizes the text. The formatted output is derived from the property method, followed by the closing tags. Listing 19.6 renders the HTML shown next ( assuming the HTML source is examined before performing a sort ):

 <center><i>Unordered List</i></center> 


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
Year: 2001
Pages: 222 © 2008-2017.
If you may any questions please contact us: