Extending Functionality with Inheritance

In addition to user controls, you can use inheritance as a technique to extend the functionality of your ASP.NET mobile Web application. If you create a class that inherits from an existing ASP.NET mobile control class, you can add additional functionality by overriding existing members or by creating new properties, methods, and events for the new class.

Creating a Class with Inheritance

The following example shows a new class, called the CarList class, which is also a List mobile control that is specialized for rendering automobile information. The CarList class encapsulates the information needed to bind to a list of Car objects.

[C#]

using System.Web.UI.MobileControls;

namespace myCompany.MobileControls
{
    class CarList : List
    {
        // Override OnInit, and set the DataValueField property
        // to the correct property of a Car object to use as the value
        // of each list item.
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.DataValueField = "id";
        }
    
        // Override OnItemDataBind, and set the list item display text
        // to a rich expression, containing the year, make, and model of
        // the car.
        protected override void OnItemDataBind(ListDataBindEventArgs e)
        {
            base.OnItemDataBind(e);

            CarInfo car = (Car)e.DataItem;
            e.ListItem.Text = 
              String.Format("{0}{1}{2}", car.Year, car.Make, car.Model);
        }
    }
}

For a more detailed example of extending the functionality of your control through inheritance, see the following Mobile Quick Starts Sample.

Deploying a New Class

To use this new class, the developer must compile the class into an assembly. In the following example, the assembly is named myCompany.CarList.dll and must be appended to the previous example code to work. You can then register the assembly on a page by using the @ Register directive, along with a custom tag, as shown in the following code.

[C#]

// Append this code to the previous example.
<%-- Registers the myCompany.MobileControls namespace. --%>
<%@ Register TagPrefix="CarCtl" Namespace="myCompany.MobileControls" Assembly="myCompany.CarList" %>
    // More code.
    <%-- Control declaration -->
    <myCompany:CarList id="myCarList" runat="server" />

If you do not provide new rendering functionality beyond the inherited rendering provided by the parent class, you do not need to write an adapter for the class. In the previous example, because every CarList control is also a list, the List adapter is automatically used. However, if you want to provide a specialized rendering of the CarList control for a given device, you can write an adapter and register the more specific mapping in the Web.config file.

See Also

Adding New Device Adapters and Device Support