Table of contents
1.
Introduction
2.
Event Handling in ASP.NET
2.1.
Arguments in Event Handling
2.2.
Application Events
2.3.
Session Events
2.4.
Page and Control Events
3.
Working Example of Event Handling
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

WebForms Event Handling in ASP.NET

Author Sneha Mallik
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The event handling-based model is used in ASP.NET Web forms. We have the ability to create any server control event. We can design an event handler to handle the click event in the instance of the button control, for example. Even ASPX pages have their own set of page life-cycle events. We all know that when a user requests an ASPX page, all of its controls are rendered as HTML controls. 

In this blog, we'll learn an event handling mechanism at work.

Event Handling in ASP.NET

Events is the means by which a process communicates. For example, interrupts are caused by the system. The application should be able to respond to and manage events when they occur. Examples of events are a mouse click, keypress, changed text, button click, mouse movements, or any other system-generated notification.

In ASP.NET, client-side events are raised and handled by the server. For example, the user might click a browser button. Then a click event occurs. The browser handles this client-side event, which sends it to the server to be processed.

The event handler is a function on the server that describes what to execute when an event is raised. As a result, when the event message is sent to the server, it checks to see if the click event has a handler associated with it. The event handler is executed if it has.

WebForms is benefited from ASP.NET's feature of event handling. It enabled us to create an event-based model for our app. We can add a simple button to an ASP.NET Web Forms page and then construct an event handler for a button's click event as a simple example. ASP.NET WebForms support both client and server events.

On the other hand, events linked with server controls in ASP.NET Web Forms pages originate on the client but are handled by the ASP.NET on the Web server.

The event-handler methods in ASP.NET WebForms follow a standard.Net Framework approach. All events take two arguments: an object that represents the object that triggered the event and an event object that contains any event-specific data.

Arguments in Event Handling

The ASP.NET event handlers require two parameters and return void. The object that is raising the event is represented by the first parameter, and the event argument is represented by the second parameter.

An event's general syntax is as follows:

private void EventName(object sender, EventArgs e);

Application Events

Some of the application events are:

  • Application_Init: When an application initializes for the first time, the Application Init event is triggered.
  • Application_Start: When an application starts for the first time, the Application Start event is fired.
  • Application_BeginRequest: Each time a new request arrives, the Application BeginRequest event is triggered.
  • Application_EndRequest: When an application closes, the Application EndRequest event is triggered.
  • Application_AuthenticateRequest: A request is ready to be authenticated when the Application AuthenticateRequest event occurs. This event can be used to check for the user's responsibilities and rights if you're using Forms Authentication.
  • Application_Error: When an unhandled error occurs in the application, the Application Error event is triggered.
  • Application_End: When the application closes or times out, the Application End event is the last of its kind. It usually provides cleanup logic for the program.

Session Events

Some of the session events are:

  • Session_Start: When a user's session is started for the first time, the Session Start event is fired. This is usually where session startup logic code is kept.
  • Session_End: When a single user Session expires or times out, the Session End Event is triggered.

Page and Control Events

Some of the common page and control events are:

  • Disposed: When the page or control is released, it is raised.
  • Data Binding: When a control binds to a data source, it raises the DataBinding event.
  • Init: When the page or control is initialized, it raises the init event.
  • Error: When an unhandled exception is thrown, an error is thrown as a page event.
  • Load: When a page or control is loaded, this event is triggered.
  • PreRender: When the page or control is about to be rendered, the PreRender event is triggered.
  • Unload: When a page or control is unloaded from memory, this event is triggered.

Working Example of Event Handling

We're going to create a click event handler here. When the user clicks the button, an event is triggered, and handler code is executed on the server.

 

// CreateEventHandling.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CreateEventHandling.aspx.cs"  
Inherits="asp.netexample.CreateEventHandling" %> 

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title>Creating an Event Handler</title> 
<style type="text/css"> 
.auto-style1 { 
	width: 100%; 
} 
.auto-style2 { 
	width: 110px; 
} 
</style> 
</head> 

<body> 
<form id="form1" runat="server"> 
<div> 
<table class="auto-style1"> 
	<tr> 
		<td class="auto-style2">Enter the first value: </td> 
		<td> 
			<asp:TextBox ID="firstvalue" runat="server"></asp:TextBox> 
		</td> 
	</tr> 
	<tr> 
		<td class="auto-style2">Enter the second value: </td> 
		<td> 
			<asp:TextBox ID="secondvalue" runat="server"></asp:TextBox> 
		</td> 
	</tr> 
	<tr> 
		<td class="auto-style2">Multiplication of values: </td> 
		<td> 
			<asp:TextBox ID="total" runat="server"></asp:TextBox> 
		</td> 
	</tr> 
	<tr> 
		<td class="auto-style2"> </td> 
		<td> 
			<br/> 
			<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"Text="Multiply"/> 
		</td> 
	</tr> 
</table> 
</div> 
</form> 
</body> 
</html>

 

// CreateEventHandling.aspx.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
namespace asp.netexample  { 
   public partial class CreateEventHandling : System.Web.UI.Page  { 
       protected void Button1_Click(object sender, EventArgs e)  { 
           int a = Convert.ToInt32(firstvalue.Text); 
           int b = Convert.ToInt32(secondvalue.Text); 
           total.Text = (a * b).ToString(); 
       } 
   } 
}

 

Output:

FAQs

1. What kinds of events do we encounter in our code?

Ans: Different kinds of events are:

  • Events required for the Server Control
    Syntax: Protected void ButtonID_Click(Object sender, EventArgs e)
  • Events required for the Page Life Cycle
    Syntax: Protected void Page_Load(Object sender, EventArgs e)  
  • Events required for the Session/Application Life Cycle
    Syntax: Protected void Application_Start(object sender, EventArgs e)

 

2. What are the common things in each function?

Ans: There are three things that each function has in common:

  • The Object Argument: The object that triggered the event is represented by the object argument.
  • The Event Args: The Event object holds any event-specific data.
  • The Name of the Event: There is a naming convention that all of these adhere to.

 

3. What are Default Events?

Ans: A default event is assigned to every control. The Page object's default event is called Load. The Click event, for instance, is the default event for the button control. 

By just double-clicking the control in the design view in Visual Studio, the default event handler can be established.

 

4. What do you mean by AutoEventWireUp property?

Ans: The page-level directive has a property called AutoEventWireUp that regulates the automatic binding of page events depending on the naming convention approach.

 

5. How does Postback help in event handling?

Ans: Postback, the process of submitting an ASP.NET page back to the server, is another item that works for us in the event handling(simply a subsequent request to a page). It informs the server that the client-side is sending data for processing back to you. Some controls support AutoPostBack, while others do not. 

 

6. How is responding to events done?

Ans: The client-side script is responsible for responding to the event. Every ASP.NET control renders an element to the browser, which triggers client-side events to manage it.

Key Takeaways

In this blog, we learned the concepts of event handling of web forms in ASP.NET. We learned about arguments in event handling as well as the application events, session events, page and control events and a working example of creating an event handler.

Take a look at our Features Of ASP Net section and see many more interesting topics related to it. Apart from that, you can refer to our Guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc.

Credits: GIPHY

Happy Developing!

Live masterclass