by May 5, 2003 0 comments

ASP.NET provides many types of controls: HTML Controls to program HTML elements, Web Server Controls with more built-in features and Validation Controls to incorporate testing logic in a control. You may encounter scenarios in which you wish to design and develop custom controls for Web-based development. 

Server control
ASP.NET provides four ways of creating a custom server control: 

  • Suppose you have created an ASP.NET page in one Application and you wish to use it in ‘as is where is’ condition in another application. ASP.NET allows you to save your page as a user control.
  • You can create a composite control if you plan to combine the features offered by two or more existing controls.
  • To enrich an existing control, you can apply the Inheritance principle. You derive a class from an existing control and then override/enhance its features.
  • If none of the above options are satisfactory, you can create a custom control by deriving from one of the base control classes.

Control creation

  • Decide the base class from your control
  • If your control has UI, override Render method and implement the UI.
  • Plan the features and design the properties, methods and events.
  • Decide how to handle the data posted back.
  • Plan client side functionality.
  • Add design-time support.

Base class 
The control that you author needn’t have user interface. Here, you will simply derive your class from System.Web.UI.Control. If your control renders UI, ensure that your control is derived from

Initializing the Control
The first step in the life cycle of a control is the firing of Init event. This is an opportunity for your control to perform any initialization. For example, you can initialize local variables. Ensure that your control does not access another server control during this event. Once the control is loaded into the Page object, the Load Event is fired. Your control typically performs actions common to all requests in this event handler, for example, populating a data set. Before the output is rendered, if you have any actions to be performed, the PreRender event is the right place. 

Persisting data across calls 
For every request made by the client, the Page object and the controls placed in it are instantiated. However, you may want to persist the values of properties across HTTP requests. ViewState is used by the page framework to automatically save the values of the page and of each control just prior to rendering to the page. The type of ViewState is System.Web.UI.StateBag. It is a dictionary that stores name/value pairs. If a control uses ViewState for property data instead of a private field, that property automatically will be persisted across round trips to the client. You do not need to use local variables here. If you wish to customize what you are storing in the view state, plan to override the SaveViewState method.

Rendering the Control
For UI Controls, Render method is the centralized location to provide the UI features of your control. What you do in this method determines the rich visual representation provided by your control. The Control class prepares an HtmlTextWriter object that manages the outgoing HTTP protocol to get text back to the browser. The main methods used during rendering are Write and WriteLine. Your task as a control writer is to use these methods to send the markup content to an output stream. If your control derives from WebControl class, you can use the AddAttributesToRender method to specify additional HTML attributes and cascading style-sheet styles to be rendered.

When the control instance is about to be released from memory, the Disposed Event is called. This is the right place to release any resources (like database connections) held by your control instance.

Postback of Events
In the ASP.NET Framework, only two HTML form elements (button and image button) cause form postback. Many a time, your custom control may not use either of these elements and yet, you may want the control to initiate postback. You can achieve this in ASP.NET through an event architecture that relies on client-side script
(JScript, JavaScript).

The following snippet of code shows (in bold) the code that must be added to the Render method of a control to initiate

protected override void Render(HtmlTextWriter output) {
output.Write("<a id =\”” + this.UniqueID + “\” href =\”javascript:” +
Page.GetPostBackEventReference(this) +”\”>”);
output.Write(" ” + this.UniqueID + “</a>”);

The GetPostBackEventReference method emits client-side script that initiates postback and also provides a reference to the control that initiated the postback event. 

Restoring ViewState
When the page is processed, the ViewState of the page and controls is hashed into a string and saved in the page as a hidden field. This hidden form field is part of the page sent to the client and the ViewState value is temporarily stored in the client’s browser. If the client chooses to post the page back to the server, the ViewState string is posted back too; upon postback, the ASP.NET page framework parses the ViewState string and populates the ViewState properties for the page and each of the controls. This implies that if you have stored a property value in ViewState, it is automatically set on post back. You do not need to do anything more here. However, if you have customized what goes into ViewState by overriding SaveViewState method, plan to override the LoadViewState method to retrieve the data.

It is a good idea to turn off ViewState if you are not using it, especially where the ViewState size is significant. You can turn off ViewState on a per-control, per-page, or even per-application basis.

Detecting State Change 
A control with UI implies that the user is likely to have entered/altered data. The control needs to examine this data; to do this, your control needs to implement the following interfaces: IPostBackDataHandler and

IPostBackDataHandler has two methods: LoadPostData and RaisePostDataChangedEvent. LoadPostData processes the postback data for the control. This is where you can compare the original data sent to client against the data modified by the client; if there is a difference, it signals a state change in the control due to which your control may want to fire an event. Make sure that you return true from LoadPostData if you have detected state change. The Page Framework calls
RaisePostDataChangedEvent only for controls that returns true from LoadPostData method. 

The RaisePostDataChangedEvent handler is a good place for your control to raise events. 

Postback Events
When posting back, the browser sends a string that identifies the specific form element that caused the postback. When postback happens, the page framework searches the posted content and determines whether a posted name corresponds to the UniqueID of a server control that implements IPostBackEventHandler. (Refer to the rendering state in which we sent the UniqueID of our control to the client.) It then invokes the RaisePostBackEvent method on that control. In this method, you can implement the logic to handle post back events.

Client-side functionality
Along with server-side processing, ASP.NET allows your control to provide rich client-side functionality. Programmatic emission of client-side scripts is an easy affair and there are many ways of doing this.

The easiest way is to use the Web Server Control’s Attributes collection. You can override the AddAttributesToRender method as follows:

protected override void AddAttributesToRender(HtmlTextWriter writer) 
writer.AddAttribute("onclick", "alert(‘Bye’);");

While the above mechanism is very simple, you may require your control to provide more complex client-side functionality. For example, you may want to provide a full-fledged client-side library. You can call Page.RegisterClientScriptBlock method so as to emit a script block. This block may contain inline script or the location of a script file.

Your control may perform specialized processing to be placed in a startup script block. This script is to be emitted at the bottom of the page so that the elements it references are guaranteed to exist. 

Also, this script is to be emitted only once, irrespective of the number of instances of your control on the page. All the above requirements are satisfied by calling Page.RegisterStartupScript method. Similarly, if your control wishes to perform some work when the form is submitted, Use the method

Design time support
In addition to rich core functionality, you should also plan the display and behavior of your custom control in a designer environment like Visual Studio.NET. Display of properties and events in a property browsers, auto-generation of code, providing custom designers to provide unique appearance and behavior are some of the key tasks in this context. 
Refer to the section titled ‘Enhancing Design 

Time Support’ in.NET Framework SDK documentation for detailed discussions and sample code on these topics.

Ease of creation
In this article, we have discussed the custom-control creation process in ASP.NET. The remarkable ease with which we can create a control with the features we have discussed in this article is something to be experienced! Going further, you may explore creating more complex controls with features like templates, composition and data binding.

Meena K, runs Symbiosis  Training and Consultancy,  Bangalore

No Comments so far

Jump into a conversation

No Comments Yet!

You can be the one to start a conversation.

Your data will be safe!Your e-mail address will not be published. Also other data will not be shared with third person.