5.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 5.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:
Create a class that inherits from the
Controlclass in theSystem.Web.UInamespace.Implement support for HTML-style attributes by adding properties to the class.
Implement an
IPostBackDataHandleras necessary to update the state of the control with the posted data.Override the
Rendermethod 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:
Register the assembly containing the control.
Insert the tag for the custom control anywhere in the page and set the attributes appropriately.
Example 5-7 and Example 5-8 show the VB and C# class files for a custom control that maintains state. Example 5-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 Example 5-10 (VB) and Example 5-11 (C#). Example 5-12
through Example 5-14 show the
.aspx and code-behind files of an application that uses ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access