Creating Server Controls


A server control trades off the ease of use of having separate UI and code elements by giving the developer tighter control of the rendering process. This control comes at a price, however: It is often more time-consuming to produce server controls than user controls. Despite the relative difficulty, many developers prefer using server controls because they are easy to share among multiple projects and the developer has precise control over the control's output and its behavior. Server controls also have the advantage of being easily bundled and can be sold to other developers by component and control vendors.

Within the narrow scope of this single chapter, you will not get a thorough and comprehensive coverage of all aspects of creating server controls within ASP.NET. However, this next section will get you started creating those controls and possibly whet your appetite for a book like Stephen Walther's ASP.NET 2.0 Unleashed (ISBN: 0672328232).

Before getting into the specifics of creating a custom server control, you should familiarize yourself with the capabilities of the WebControl class. You create custom server controls by creating classes that inherit from WebControl. Tables 30.1 and 30.2 contain a list of commonly used properties and methods of the WebControl class.

Table 30.1. WebControl Properties

Property

Description

AccessKey

The key that allows quick access to the control.

BackColor

The background color used for the control.

BorderColor

The control's border color.

BorderStyle

The control's border style.

BorderWidth

The control's border width.

Controls

A collection of the child controls contained within the control.

CssClass

The Cascading Style Sheet (CSS) used by the control.

Enabled

Boolean indicating whether the control is enabled.

EnableTheming

Enables support for ASP.NET 2.0 themes.

EnableViewState

Indicates whether view state is active for this control.

Font

The control's font.

ForeColor

The control's foreground color.

ID

The control's ID.

SkinID

The currently selected skin for the control.

ToolTip

The ToolTip for the control displayed when the mouse hovers over the control.

Visible

Indicates whether the control is rendered visibly on the page.

Width

The control's width.


Table 30.2. WebControl Methods

Method

Description

DataBind

Binds a data source to the control.

Focus

Sets the current input focus to the control.

HasControls

Indicates whether the control contains child controls.

RenderBeginTag

Renders the HTML tag used to begin the rendering of the control. Default tag is <span>.

RenderControl

Outputs the control contents.

RenderEndTag

Renders the HTML completion tag that wraps the control. Default is </span>.


As you saw in the preceding example, you can define properties on a control class that can be set declaratively at design time or programmatically at runtime. With a custom server control, it is more difficult to determine the context of those properties because you don't have editable access to the control tree at design time as you do with a web user control. To help the user figure out what each property means and how it should be used, there are several attributes that you can use to decorate a server control property. Some of the more common ones are

  • Bindable This attribute indicates whether the associated property can be bound to a data source.

  • Category This attribute indicates the category within the property editor in which the property should appear. For example, properties such as Font, ForeColor, and BackColor all show up in the Appearance category.

  • DefaultValue This attribute indicates the default value of the property when no value has been supplied at design time or runtime.

  • Description This attribute provides a long description of the property.

  • Localizable This attribute indicates whether the property will have different values based on different cultural locations and language settings.

To follow along, add a new Class Library project to the solution in which the control website was created. Add a reference to System.Web from within this class library and you're ready to start creating server controls in this library.

Add a new class to the class library called TextBoxButton. This class is going to be a server control that will contain a text box and a button to illustrate the principle of a custom server control with child controls. In addition, you will also see how to "bubble" events from within a server control up to the page in which the control resides.

Make sure the code for the TextBoxButton class looks like the code in Listing 30.1.

Listing 30.1. The TextBoxButton Class

using System; using System.ComponentModel; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; /// <summary> /// Summary description for TextBoxButton /// </summary> namespace CustomControls { public class TextBoxButton : WebControl { public event EventHandler buttonClick; private Button btn; private TextBox txBox; public TextBoxButton() {     //     // TODO: Add constructor logic here     // } [Bindable(true),    Category("Appearance"),    DefaultValue("Button"),    Description("The Text on the Button"),    Localizable(true)] public string ButtonText {     get { EnsureChildControls(); return btn.Text; }     set { EnsureChildControls(); btn.Text = value; } } [Bindable(true),    Category("Appearance"),    DefaultValue(""),    Description("The Text within the Text Box"),    Localizable(true)] public string Value {     get { EnsureChildControls(); return txBox.Text; }     set { EnsureChildControls(); txBox.Text = value; } } protected override void CreateChildControls() {     txBox = new TextBox();     Controls.Add(txBox);     btn = new Button();     btn.Click += new EventHandler(btn_Click);     Controls.Add(btn); } protected override void RenderContents(HtmlTextWriter writer) {     base.RenderContents(writer); } void btn_Click(object sender, EventArgs e) {     if (buttonClick != null)         buttonClick(sender, e); } } } 

However tempting it may be, you should never instantiate new child controls from within a control's constructor. It is often difficult to remember that the instantiation and configuration of controls is done in an entirely separate stage of the control life cycle than the rendering. Because of this, use the CreateChildControls method to establish the control tree and use the RenderContents method to make any specific changes to the child controls.

In Listing 30.1 the property definitions should be fairly self-explanatory. The property values are derived from property values on child controls, and thus require the use of the EnsureChildControls() method to make sure that the child controls exist before retrieving or setting their properties.

To let the page hosting the control respond to the event when a user clicks the nested button within TextBoxButton, you need to support a process called "bubbling." When an event is fired and handled within one class and that class then publishes an event representing the same occurrence to another class, the event is considered to be "bubbled." The phrase comes from an analogy related to bubbles rising to the surface of a liquid.

For this control to support event bubbling, it needs to publish an event using the following line of code:

public event EventHandler buttonClick; 


When this control handles the Click event from the child Button control, it allows any container control to respond to the same event by bubbling it up one level:

void btn_Click(object sender, EventArgs e) {     if (buttonClick != null)         buttonClick(sender, e); } 


Build the class library and then add a reference to the CustomControls project from the web application project. After building the solution this way, create a new Web Form. An extremely useful feature is that the Toolbox has detected the presence of a web control within an assembly in the solution and has added it in a category called "ControlsDemo Components" (assuming your web project is called ControlsDemo).

When you drag the control from the special category on the control Toolbox, you will see a preview of the control's rendered output using default values. The Properties Editor panel will contain all of the custom properties that you defined on your control and will reflect the settings of the custom attributes applied to those properties, as shown in Figure 30.2.

Figure 30.2. Properties Editor panel for a custom server control.


Using your knowledge of C#, object-oriented programming, the ASP.NET page life cycle, and the functionality and features of the WebControl class, you can create some very powerful controls.



Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

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