New Document
Understanding event handling in ASP.NET

What is an Event?

ASP.NET provides an event-based programming model that simplifies Web programming. In my previous article "ASP.NET: Revolution, not evolution," I demonstrated a simple ASP.NET Greeter application that handled a single button click event. In that application, event handlers were attached to the button Web server control programmatically.

In this article, I'll expand on that application to demonstrate how to attach event handlers declaratively for control-level and page-level events. I'll also discuss the overall structure of an ASP.NET application and demonstrate the events you can handle throughout its life cycle.

Declaratively attaching event handlers

Let's take a look at the revised Greeter page. Recall that the page is split into the UI, in Greeter.aspx shown in Listing A, and the logic, in the GreeterLogic class in Greeter.aspx.cs, shown in Listing B. The UI and logic are joined through inheritance specified in the @ Page directive at the top of Greeter.aspx. Rather than attach the button click handler manually via a delegate in GreeterLogic.OnInit (I've left this code in OnInit, commented out at Note 1), the event handler is attached declaratively in Greeter.aspx. The Web server control, declared inside the

tag, contains the attribute OnClick="Button_Click". When the ASP.NET run time processes Greeter.aspx, it generates a .NET class that automatically does what I previously did manually: It creates a delegate for the Button_Click method in the base class GreeterLogic and adds it to the button click event.

A bit less work is a good thing, right? Maybe, but there's another consideration-one to watch out for. Because the .NET class is created dynamically on the first access to the page, errors, like a typo in the event handler name, won't be discovered until run time.

Event is an action or occurrence like mouse click, key press, mouse movements, or any system generated notification. The processes communicate through events. For example, Interrupts are system generated events. When events occur the application should be able to respond to it.

In ASP.Net an event is raised on the client, and handled in the server. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server.

The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler, and if it has, the event handler is executed.

Asp.Net bases on Events. These are actions that occur on objects such a mouse click on a button. Below is an example of some of the events available:

OnClick                                                       Execute when a button is clicked

OnSelectedIndexChanged                             Executes when an option in dropdownlist is selected

OnCheckChanged                                        Executes when a checkbox or radiobutton are checked


Subroutine: Sub program that can take data called parameters (optional) and execute a task. It does not return a value. Subroutines are used to define event handlers.


Sub AnyNameHere(info As String)


End Sub

Event Arguments:

ASP.Net event handlers generally take two parameters and return void. The first parameter represents the object raising the event and the second parameter is called the event argument.When an event is triggered it requests a piece of program to be executed. If you want an email to be sent you must click on the send button, this is linked to a program that will send the email over the internet. These programs are called Event Handlers, they execute at an events request. Below is an example of pre-defined Event Handlers:

Page_Load                    Executes when the page load

Page_Unload                Executes when the page is close

The general syntax of an event is:

private void EventName (object sender, EventArgs e);
Application and Session Events:

The most important application events are:

  • Application_Start . it is raised when the application/website is started

  • Application_End . it is raised when the application/website is stopped

Similarly, the most used Session events are:

  • Session_Start . it is raised when a user first requests a page from the application

  • Session_End . it is raised when the session ends

Page and Control Events:

Common page and control events are:

  • DataBinding . raised when a control bind to a data source

  • Disposed . when the page or the control is released

  • Error . it is an page event, occurs when an unhandled exception is thrown

  • Init . raised when the page or the control is initialized

  • Load . raised when the page or a control is loaded

  • PreRender . raised when the page or the control is to be rendered

  • Unload . raised when the page or control is unloaded from memory

Event Handling Using Controls:

All ASP.Net controls are implemented as classes, and they have events which are fired when user performs certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling these events there are in-built attributes and event handlers. To respond to an event, the event handler is coded.

By default Visual Studio creates an event handler by including a Handles clause on the Sub procedure. This clause names the control and event that the procedure handles.

Sub BTN_Click(sender as Object, e as EventArgs)

End Sub


Note that the event handler passes two arguments; sender as Object represents the object raising the event. And e as EventArgs represents the data specific to the event which is being sent to the server (if any). This is called Event Argument.

The asp tag for a button control:

<asp:Button ID="btnCancel" runat="server" Text="Cancel" />

The event handler for the Click event:

Protected Sub btnCancel_Click(ByVal sender As Object, 
                              ByVal e As System.EventArgs) 
                              Handles btnCancel.Click
End Sub

An event can also be coded without a Handles clause. Then the handler must be named according to the appropriate event attribute of the control.

The asp tag for a button control:

<asp:Button ID="btnCancel" runat="server" Text="Cancel" 
                              Onclick="btnCancel_Click" />

The event handler for the Click event:

Protected Sub btnCancel_Click(ByVal sender As Object, 
                              ByVal e As System.EventArgs)
End Sub

The common control events are:

EventAttributeControls
ClickOnClickButton, image button, link button, image map
CommandOnCommandButton, image button, link button
TextChangedOnTextChangedText box
SelectedIndexChangedOnSelectedIndexChangedDrop-down list, list box, radio button list, check box list.
CheckedChangedOnCheckedChangedCheck box, radio button

Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click events like, Button.Click. Some events are not posted back to the server immediately, these are called non-postback events.

For example, the change events or selection events, such as, TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true.

Default Events:

The default event for the Page object is the Load event. Similarly every control has a default event. For example, default event for the button control is the Click event.

The default event handler could be created in Visual Studio, just by double clicking the control in design view. The following table shows some of the default events for common controls:

ControlDefault Event
AdRotatorAdCreated
BulletedListClick
ButtonClick
CalenderSelectionChanged
CheckBoxCheckedChanged
CheckBoxListSelectedIndexChanged
DataGridSelectedIndexChanged
DataListSelectedIndexChanged
DropDownListSelectedIndexChanged
HyperLinkClick
ImageButtonClick
ImageMapClick
LinkButtonClick
ListBoxSelectedIndexChanged
MenuMenuItemClick
RadioButtonCheckedChanged
RadioButtonListSelectedIndexChanged
Example:

This example has a simple page with a label control and a button control on it. As the page events like, Page_Load, Page_Init, Page_PreRender etc. takes place, it sends a message, which is displayed by the label control. When the button is clicked, the Button_Click event is raised and that also sends a message to be displayed on the label.

Create a new website and drag a label control and a button control on it from the control tool box. Using the properties window, set the IDs of the controls as .lblmessage. and .btnclick. respectively. Set the Text property of the Button control as 'Click'.

The markup file (.aspx):

<%@ Page Language="C#" AutoEventWireup="true" 
                          CodeBehind="Default.aspx.cs" 
                          Inherits="eventdemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:Label ID="lblmessage" runat="server" >
     </asp:Label>
        <br />
        <br />
        <br />
     <asp:Button ID="btnclick" runat="server" Text="Click" 
                 onclick="btnclick_Click" />
    </div>
    </form>
</body>
</html>

Double click on the design view to move to the code behind file. The Page_Load event is automatically created without any code in it. Write down the following self-explanatory code lines:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace eventdemo
{
public partial class _Default : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
     lblmessage.Text += "Page load event handled. <br />";
     if (Page.IsPostBack)
     {
       lblmessage.Text += "Page post back event handled.<br/>";
     }
  }
  protected void Page_Init(object sender, EventArgs e)
  {
    lblmessage.Text += "Page initialization event handled.<br/>";
  }
  protected void Page_PreRender(object sender, EventArgs e)
  {
    lblmessage.Text += "Page prerender event handled. <br/>";
  }
  protected void btnclick_Click(object sender, EventArgs e)
  {
    lblmessage.Text += "Button click event handled. <br/>";
  }
 }
}

Run the page. The label shows page load, page initialization and the page pre-render events. Click the button to see effect:

ASP.NET Event Example


Previous                                                                                                                                                       Next

Back to Top