This section introduces you to ASP.NET event handling.
An event is an action or occurrence, such as a mouse click, key press, mouse movement, or any system-generated notification. A process communicates through events. For example, interrupts are system-generated events. When events occur, applications can respond and manage them.
Events on ASP.NET are raised on the user's machine and processed on the server. For example, a user clicks a button displayed in a browser. A click event is raised. The browser handles this client-side event by sending it to the server.
The server has a subroutine that describes what to do when an event is raised; this is called an event handler. Therefore, when the event information is passed to the server, it checks whether the click event is associated with an event handler. If relevant, the event handler will be executed.
ASP.NET event handlers typically take two parameters and return null. The first parameter represents the object firing the event, and the second parameter is the event parameter.
The general syntax for an event is:
private void EventName (object sender, EventArgs e);
The most important application events are:
Application_Start - Raised when an application or web page is launched.
Application_End - Raised when stopping an application or web page.
Likewise, the most commonly used session events are:
Session_Start – Fired when the user initially requests a page from the application.
Session_End – Raised when the session ends.
Common page and control events are:
DataBinding – Raised when a control is bound to a data source.
Disposed – Raised when the page or control is released.
Error – It is a page event that occurs when there is an unhandled exception.
Init – Raised when initializing a page or control.
Load – Raised when a page or control is loaded.
PreRender – Raised when the page or control is displayed.
Unload – Raised when a page or control is unloaded from memory.
All ASP.NET controls are implemented as classes, and they raise events when the user performs a specific action on them. For example, when a user clicks a button, a 'Click' event is generated. For handling events, there are built-in properties and event handlers. Event handling applications are coded to respond to an event and take appropriate action on it.
By default, Visual Studio creates an event handler that includes a subroutine that handles the clause. This clause names the controls and events that the program handles.
ASP tag for button control:
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
Event handling application for Click event:
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.ClickEnd Sub
An event can also be encoded without a Handles clause. The handler must then be named after the appropriate event that fits the control's property.
ASP tag for button control:
<asp:Button ID="btnCancel" runat="server" Text="Cancel" Onclick="btnCancel_Click" />
Event handling application for Click event:
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)End Sub
Common control events include:
event | property | control |
---|---|---|
Click | OnClick | button, image button, link button, image bitmap |
Command | OnCommand | button, image button, link button |
TextChanged | OnTextChanged | text box |
SelectedIndexChanged | OnSelectedIndexChanged | Dropdown menu, listbox, radio button list, listbox with checkboxes |
CheckedChanged | OnCheckedChanged | checkbox, radio button |
Some events cause the form to be posted back to the server immediately, these are called callback events. For example, click events like Button.Click.
Some events are not sent back to the server immediately. These are called non-callback events.
For example, change events or selection events like TextBox.TextChanged or CheckBox.CheckedChanged. These non-callback events can be immediately called back by setting their AutoPostBack property to true.
The default event for page objects is the load event. Similarly, every control has a default event. For example, the default event for a button control is the Click event.
Default event handlers can be created in Visual Studio simply by double-clicking a control in Design view. The following table shows the default events for a list of common controls:
control | default event |
---|---|
Advertising control (AdRotator) | AdCreated |
Item List (BulletedList) | Click |
Button | Click |
Calendar control (Calender) | SelectionChanged |
CheckBox | CheckedChanged |
CheckBoxList | SelectedIndexChanged |
DataGrid | SelectedIndexChanged |
DataList | SelectedIndexChanged |
DropDownList | SelectedIndexChanged |
HyperLink | Click |
ImageButton | Click |
Hotspot (ImageMap) | Click |
Hyperlink button (LinkButton) | Click |
Single or multiple selection drop-down list (ListBox) | SelectedIndexChanged |
Menu | MenuItemClick |
RadioButton | CheckedChanged |
Radio button group (RadioButtonList) | SelectedIndexChanged |
Example
This example includes a simple page with control labels and a button control. When page events, such as Page_Load, Page_Init, Page_PreRender, etc., occur, it will send a message, which will be displayed by the label control. When a button is clicked, the Button_Click event is raised, also sending a message displayed by the label.
Create a new website and drag a Label control and Button control from the Controls tool box. Using the window properties, set the control IDs to .lblmessage. and .btnclick accordingly. Set the button control's text property to "Click".
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 the design view and move to the code behind the file. The Page_Load event is created automatically without any code. Write the following self-explanatory line of code:
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/>"; } }}
Execute page. Tags show page load, page initialization, and page preview events. Click the button to see the effect: