When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML
Information:
Advertise
Feedback
Author an Article

ASP ASP.NET ASP FAQs Message Board Feedback
 
Print this Page!
Published: Wednesday, October 1, 2003

Easily Adding Functionality to ASP.NET Server Controls

By Scott Mitchell


Introduction


Have you ever found yourself using one of the built-in ASP.NET server controls and needed to add some trivial extra functionality? For example, maybe for a Button Web control you wanted a confirm client-side dialog box to appear, requiring the user to click OK to actually submit the form, or maybe you wanted to enhance the DataGrid's output so that whenever the user moused over a cell, the cell's background color changed to a "highlighted" color.

- continued -

Typically this is accomplished by overriding the proper event in the server control class, and manually adding the extended functionality. For example, to provide cell-highlighting with the DataGrid you would override the DataGrid's ItemCreated event and set the Attributes property of the DataGridItem's various Cells so that their onmouseover and onmouseout client-side events triggered the desired color highlighting.

The disadvantage of this approach is that it requires a bit of coding each and every time you want to use the functionality. That is, if you have a number of ASP.NET Web pages where you want to use this enhanced DataGrid, you have to make these additions by hand on each page. While this is not terribly difficult, it can get time-consuming, and tedious, especially if after making these changes you decide to not do the highlighting after all. A less tedious approach is to create a new ASP.NET server control, one that takes all of the functionality of the base server control, and extends it by adding on this one little bit of extra functionality. With this approach, you write the code once, compile the new server control, and then can reuse the server control on any number of ASP.NET Web pages without adding anything extra.

In this article we'll examine how to improve the functionality of the Calendar Web control by adding a property called HoverColor. If this property is set, whenever the user moves their mouse over a day in the Calendar control, that day becomes "highlighted" with the specified color. Our discussion of adding this functionality will look at inheritance, adding properties to Web controls, and a brief look at maintaining property state in Web controls across postbacks.

Adding Functionality with Inheritance


One of the more powerful features of object-oriented programming lies in inheritance. The concept of inheritance stems from the fact that complex objects are extensions of simple ones. For example, the Hummer is an extension of a standard SUV; a standard SUV is an extension of a standard pickup truck; a pickup truck is an extension of a standard automobile. Inheritance makes design and implementation much easier because it gives designers and engineers a starting point. That is, when building a Hummer, the engineers already have the base components done for them: they don't need to worry about the dynamics of the internal combustion engine, or the computer system that works the fuel injector.

Since .NET is a fully object-orientized platform, it should come as no surprise that the ASP.NET object model is ripe with possibilities for extension via inheritance. Just look at the provided ASP.NET server controls. All server controls are extended, either directly or indirectly, from the System.Web.UI.Control class. This class provides the base functionality all ASP.NET server controls need to perform in the life cycle of an ASP.NET Web page. This class is refined further with the System.Web.UI.WebControls.WebControl class, which adds style information, such as background color, forecolor, font information, and such, to the base properties defined by the Control class.

In a similar vein, we can take an existing ASP.NET server control class, such as the Calendar or DataGrid or TextBox, and create a new class derived from this base class. Automatically, without having to write a single line of code, this inheritance gives our new server control all of the functionality provided in the base class. Therefore, to add new functionality we only need to write the code necessary for said new functionality - and with that little addition, we'll have a fully robust, useable Web control similar to the base control in all ways except now that its functionality has been extended.

This article isn't meant as an in-depth look at inheritance - for more on that topic be sure to read Ian Stalling's article Using Object-Orientation in ASP.NET: Inheritance.

Recommended First Step: Create the Desired Added Functionality in an ASP.NET Web Page


Before even considering creating a custom server control, I would first recommend adding the desired functionality through an ASP.NET Web page. This will allow you to see what series of steps need to be taken to add the functionality. Recall that for this article we're going to create an enhanced Calendar that "highlights" the day the mouse is over.

Before examining the code to add this functionality, let's take a moment to discuss the Calendar Web control. The calendar is rendered as an HTML table. The days of the month are rendered as individual table cells. The Calendar class provides a DayRendered event which fires once for every day added to the month during the control's life cycle. This event handler is passed information about the day being rendered, including a reference to the TableCell class. Therefore, in our ASP.NET Web page we can create an event handler for this event and programmatically alter the TableCell instance to provide "highlighting" capabilities when the mouse is hovered over the day. Specifically, this highlighting functionality can be accomplished with client-side onmouseover and onmouseout events that change the cell's style.backgroundColor client-side JavaScript property.

To add this functionality in an ASP.NET Web page, we first need to add a Calendar Web control, which can be accomplished with the following syntax:

<form id="Form1" method="post" runat="server">
   <asp:Calendar id="Calendar1" runat="server"
        OnDayRender="CreateDayEffects">
   </asp:Calendar>
</form>

As this code shows, the Calendar class must be placed within a Web Form. Furthermore, the Calendar's DayRender event is tied to an event handler, CreateDayEffects. The code for CreateDayEffects is shown below. Namely, it sets the client-side onmouseover and onmouseout events via the TableCell class's Attributes property:

private void CreateDayEffects(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
   e.Cell.Attributes["onmouseover"] = "this.style.backgroundColor='pink';";
   if (Calendar1.DayStyle.BackColor != Color.Empty)
      e.Cell.Attributes["onmouseout"] = "this.style.backgroundColor='" + 
                 Calendar1.DayStyle.BackColor.ToKnownColor() + "';";
   else
      e.Cell.Attributes["onmouseout"] = "this.style.backgroundColor='';";
}
[View a Live Demo!]

Adding this functionality in an ASP.NET Web page alludes to the steps we'll need to perform in our custom server control. Furthermore, it identifies places that we'll want to allow the page developer to customize. For example, in the ASP.NET example, notice that the highlighted color is hard-coded as pink. In our custom control, we'll want to make this color customizable, so that the page developer can indicate the hover color.

Building the Custom Server Control Class


The New Project dialog box. Building the custom server control class is relatively simply, especially with Visual Studio .NET. If you are using VS.NET, start by creating a new Web Control Library project in either C# or VB.NET (we'll be examining C# code in this article). Name the project skmCalendar. (The screenshot to the right shows the New Project dialog box in Visual Studio .NET 2003.)

This will create a class with the custom Web control template. You can go ahead and replace that code with the following:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing;

namespace skmCalendar
{
   [ ToolboxData("<{0}:HoverCalendar runat=server></{0}:HoverCalendar>")]
   public class HoverCalendar : System.Web.UI.WebControls.Calendar
   {
      [Bindable(true),
         Category("Appearance"),
         DefaultValue("")]
      public Color HoverColor
      {
         get
         {
            // look for hover color in ViewState
            object o = ViewState["HoverColor"];
            if (o == null)
               return Color.Empty;
            else
               return (Color) o;
         }

         set
         {
            ViewState["HoverColor"] = value;
         }
      }

      
      // override the DayRender function
      protected override void OnDayRender(TableCell cell, CalendarDay day)
      {
         if (HoverColor != Color.Empty)
         {
            cell.Attributes["onmouseover"] = "this.style.backgroundColor='" + 
                      String.Format("#{0:x2}{1:x2}{2:x2}", 
                          this.HoverColor.R, this.HoverColor.G, this.HoverColor.B) + "';";
            if (this.DayStyle.BackColor != Color.Empty)
               cell.Attributes["onmouseout"] = "this.style.backgroundColor='" + 
                      String.Format("#{0:x2}{1:x2}{2:x2}", 
                        this.DayStyle.BackColor.R, this.DayStyle.BackColor.G, 
                        this.DayStyle.BackColor.B) + "';";
            else
               cell.Attributes["onmouseout"] = "this.style.backgroundColor='';";
         }

         base.OnDayRender (cell, day);
      }

   }
}

First off, notice just how little code we needed to write. This is because this class we created, HoverCalendar, is derived from the Calendar class, thereby incorporating all of its base functionality. All we have to do is provide a property that the user can utilize to specify the hover color (this property is called HoverColor), and then we override the OnDayRender method.

Let's look at both the property and the overridden method in more detail. Note that the HoverColor uses the ViewState as a backing store for its value. That is, in the get accessor, the property checks to see if there exists some Color instance in ViewState["HoverColor"]. If there does, then this value is returned, else the default value - Color.Empty - is returned instead.

The reason we use the ViewState as a backing store is so that if the property value is changed programmatically by the page developer that it is persisted across postbacks. For simple, scalar properties - like strings, numbers, Colors, and so on - simply storing the item in the ViewState is sufficient to maintain changed state across postbacks. However, for more complex properties - like properties that are class instances themselves - a more involved state management technique is required. A thorough discussion on this is far beyond the scope of this article. If you are interested in learning more, I highly recommend Nikhil Kothari and Vandana Datye's Developing Microsoft ASP.NET Server Controls and Components.

The HoverCalendar also contains an overridden form of the OnDayRender method. OnDayRender is a function that executes whenever the DayRender event fires, so we can tap into this event's firing by overriding the OnDayRender method. Inside this method we need to set the cell's onmouseover and onmouseout client-side events, just like we did in the ASP.NET Web page example. This time, however, we set it based on the color of the HoverColor property. (The String.Format() method transforms a Color instance to the Web-specification for colors as #RRGGBB.) Note that at the end of the overridden method, we call base.OnDayRender (cell, day);, which call's the base class's OnDayRender method.

Building and Deploying the HoverCalendar Server Control


To build the server control, go to the Build menu in Visual Studio .NET and select Build Solution. This will create a file named skmCalendar.dll. To use this control in an ASP.NET Web page, first open up the ASP.NET Web Application in Visual Studio .NET. Next, right-click on the References folder in the Solution Explorer and browse to the skmCalendar.dll file. You'll also want to add the HoverCalendar control to the Toolbox by right-clicking on the Toolbox, choosing to configure the toolbox, and then navigating to the skmCalendar.dll file. Once the HoverCalendar has been added to the Toolbox, you can simply drag and drop it onto the Design view of an ASP.NET Web page. From the Design view, the page developer can set the HoverCalendar's controls just like you would for the standard Calendar Web control.

If you are not using Visual Studio .NET, you will need to build the server control via the command-line compiler. Assuming you saved the class file as HoverCalendar.cs, use the following command-line syntax:

csc /t:library /r:System.dll,System.Drawing.dll,System.Web.dll /out:skmCalendar.dll HoverCalendar.cs

To deploy this custom control, you need to copy the skmCalendar.dll file to the Web application's /bin directory. Then, to use it in an ASP.NET Web page, add the following syntax at the top of the page:

<%@ Register TagPrefix="skm" Namespace="skmCalendar" Assembly="skmCalendar" %>

Then, in the ASP.NET Web page, wherever you want the HoverCalendar to appear, use:

<skm:HoverCalendar runat="server" ... />

Conclusion


In this article we looked at how to add functionality to an existing ASP.NET Web control by using inheritance to build our own extended version of the Web control. Specifically in this article we looked at how to extend the built-in Calendar control to provide "highlighting" of the day of the month that currently had the mouse hovering over it. Another article I authored, Injecting Client-Side Script from an ASP.NET Server Control, I look at how to extend the base functionality of the Button Web control to provide client-side confirmation when the button is clicked (a JavaScript confirm() dialog box). The important concept to take away is that inheritance, a hallmark of object-oriented programming, makes it a breeze to add functionality to an existing object.

By building a custom server control, the extended functionality can be easily and quickly deployed to multiple ASP.NET Web applications and multiple ASP.NET Web pages within those Web applications. To customize the "highlight" color for the HoverCalendar control, the page developer need to only set the HoverColor property (either programmatically, declaratively, or through the Design view). Had we left this extra functionality in the ASP.NET Web page code itself, this code would need to be replicated in each ASP.NET Web page that wished to utilize the enhanced Calendar, and the hover color would need to be specified as a hard-coded value in each page.

Happy Programming!

  • By Scott Mitchell


    Attachments:


  • Download the Visual Studio .NET 2003 Project for the HoverCalendar custom control (ZIP file)



  • ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article