6.4. Using the Control State with Custom Controls

Problem

You want to allow users to disable the ViewState for your custom control but you do not want to lose functionality when they do. In other words, when a developer disables the ViewState for the page or your custom control, you want to be able to maintain critical state information for your control.

Solution

Create a custom control like the one described in Recipe 6.3, register the control with the Page indicating the control requires use of the Control State, override the SaveControlState method to save the critical information for your control in the Control State, and override the LoadControlState method to reload the critical information from the Control State on postback.

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 state support as described in Recipe 6.3.

  3. In the control Init method, register the control with the Page indicating the control requires use of the Control State.

  4. Override the SaveControlState method to save the critical information for your control in the Control State.

  5. Override the LoadControlState method to reload the control information from the Control State on postback.

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-15 and 6-16 show the VB and C# class files for ...

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.