Extending Functionality with Inheritance

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

Creating a Class with Inheritance

The following code example shows a new class named CarList that inherits from the List mobile control and that is specialized for rendering automobile information. The CarList class encapsulates the information needed to bind to a list of Car objects.

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 ASP.NET Mobile Quickstart tutorials.

Deploying a New Class

To use this example class, compile the class into an assembly and put it into the application's Bin folder. The following example shows how to register an assembly named MyCompany.CarList.dll. You register the assembly on a page using the @ Register directive, specifying a custom tag.

<%-- Register the myCompany.MobileControls namespace. --%>
<%@ Register TagPrefix="car" Namespace="myCompany.MobileControls" 
    Assembly="myCompany.CarList" %>
    // More code.
    <%-- Control declaration --%>
    <car:CarList id="myCarList" runat="server" />

If your inherited control does not modify the rendering functionality of 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 object, the adapter assigned to the List control for the current browser, such as the HtmlListAdapter, is automatically used. However, if you want to provide specialized rendering of the CarList control for a specific device, you can write an adapter and register the mapping in the Web.config file.

See Also

Other Resources

Adding New Device Adapters and Device Support

Creating Custom Mobile Controls