Parsing Inner Content


Thus far, you have seen how to use properties to add values to a control. In this section, you explore how to assign values to a control by adding the values between a control's opening and closing tags.

Every control has a Controls collection that represents all of its child controls. When you add text between the opening and closing tags of a control, the text is added as a LiteralControl to the Controls collection. If you add text and, say, a TextBox control, two controls are added to the Controls collection: LiteralControl and TextBox .

The control in Listing 28.9, for example, displays whatever text appears between its opening and closing tags in a bold green font.

Listing 28.9 ShowGreen.vb
 Imports System Imports System.Web Imports System.Web.UI Namespace myControls Public Class ShowGreen: Inherits Control Protected Overrides Sub Render( objTextWriter As HtmlTextWriter )   Dim strInnerText As String   If IsLiteralContent     strInnerText = CType( Controls( 0 ), LiteralControl ).Text     objTextWriter.AddAttribute( "color", "green" )     objTextWriter.RenderBeginTag( "font" )     objTextWriter.RenderBeginTag( "b" )     objTextWriter.Write( strInnerText )     objTextWriter.RenderEndTag()     objTextWriter.RenderEndTag()   End If End Sub End Class End Namespace 

The C# version of this code can be found on the CD-ROM.

In the Render method in Listing 28.9, the IsLiteralContent method checks whether the control contains literal content between its opening and closing tags. If the control contains a single LiteralControl control, the IsLiteralContent method returns True .

LiteralControl is retrieved from the Controls collection, converted to the right type, and the value of its Text property is assigned to a variable named strInnerText . The value of the strInnerText variable is output using a bold green font.

The page in Listing 28.10 demonstrates how you can use the ShowGreen control with an ASP.NET page.

Listing 28.10 DisplayShowGreen.aspx
 <%@ Register TagPrefix="myControls" Namespace="myControls" Assembly="ShowGreen"%> <html> <head><title>DisplayShowGreen.aspx</title></head> <body> <myControls:ShowGreen   Runat="Server">   Hello World! </myControls:ShowGreen> </body> </html> 

The C# version of this code can be found on the CD-ROM.

When the page in Listing 28.10 is displayed, the text that appears between the opening and closing ShowGreen tags is displayed with a bold green font. Because you use the IsLiteralContent method in the control's Render method, placing any other control within the opening and closing tags would prevent the control from displaying anything.



ASP.NET Unleashed
ASP.NET 4 Unleashed
ISBN: 0672331128
EAN: 2147483647
Year: 2003
Pages: 263

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net