6.3. Creating a Custom Control with State

Problem

You want to create a custom control that remembers its state between postbacks of a form, like the server controls provided with ASP.NET.

Solution

Create a custom control like the one described in Recipe 6.2, implement the IPostBackDataHandler interface to add the functionality to retrieve the values posted to the server and then update the values in the custom control from the postback data.

Use the .NET language of your choice to:

  1. Create a class that inherits from the WebControl class in the System.Web.UI.WebControls namespace.

  2. Implement support for HTML-style attributes by adding properties to the class.

  3. Implement an IPostBackDataHandler as necessary to update the state of the control with the posted data.

  4. Override the RenderContents method to have it render the HTML output of the control using the values of the properties.

To use the custom control in an ASP.NET page:

  1. Register the assembly containing the control.

  2. Insert the tag for the custom control anywhere in the page and set the attributes appropriately.

Examples 6-7 and 6-8 show the VB and C# class files for a custom control that maintains state. Example 6-9 shows how we use the custom control in an ASP.NET page.

A version of the custom control that maintains state and provides the added ability to raise an event when the control data has changed is shown in Examples 6-10 (VB) and 6-11 (C#). Examples 6-12, 6-13 through 6-14 show the .aspx and code-behind files of an application that ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.