A Trivial Server Control Example


To demonstrate the mechanics of implementing a control, we'll start by creating a very simple server control that merely renders a text string to the client. Our control derives from the base Control class to participate in the HTTP request/response processing provided by the page framework and overrides the inherited Render method to write to the output text stream. Listing 5-1 shows the code for our control.

Listing 5-1 SimpleControl.cs
 usingSystem; usingSystem.Web.UI; namespaceMSPress.ServerControls{ publicclassSimpleControl:Control{ protectedoverridevoidRender(HtmlTextWriterwriter){ writer.Write("Idon'tdoanythinguseful,"); writer.Write("butatleastI'macontrol..."); } } } 

Note

If you are using Visual Studio .NET, start a new Microsoft Visual C# Control Library project, delete the designer-generated code in WebCustomControl1.cs, and replace it with the code we provide for the control.


System.Web.UI.HtmlTextWriter is a utility class that encapsulates the functionality of writing HTML to a text stream. In Chapter 8, "Rendering," we will show you how to use the methods of the HtmlTextWriter class to simplify HTML rendering. For now, SimpleControl simply passes text into the Write method of the HtmlTextWriter instance. The Write method outputs the specified text to the HTTP response stream and is equivalent to the Response.Write method in traditional Active Server Pages programming. Do not directly invoke Page.Response.Write from your controls because doing so breaks the encapsulation provided by the page framework. Instead, override one of the rendering methods provided by the Control or WebControl class to write to the response stream. We'll explain the rendering process in greater detail in Chapter 8.

The using declarations enable you to access types by shorter names instead of their fully qualified class names . Thus, Control is equivalent to System.Web.UI.Control . The using declarations do not add any overhead, and they make your code more readable. You must declare your control in a namespace so that page developers can use your control declaratively on pages, as you will soon see.

The Render method, which SimpleControl overrides, corresponds to the Render phase in a control's life cycle. A control writes text to the underlying HTTP response stream during this phase.



Developing Microsoft ASP. NET Server Controls and Components
Developing Microsoft ASP.NET Server Controls and Components (Pro-Developer)
ISBN: 0735615829
EAN: 2147483647
Year: 2005
Pages: 183

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