Event Handlers in C#

An event handler is a callback routine that operates asynchronously and handles inputs received into a program (events).

You can create server event handlers for controls and for the page in a variety of ways.

in the below example, in Button1_Click, Button2_Click event is also executed.

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

<head runat=”server”>
<title>Event Handlers</title>
<form id=”form1″ runat=”server”>
<asp:Button ID=”Button1″ runat=”server” OnClick=”Button1_Click” Text=”Button1″ />
<asp:Button ID=”Button2″ runat=”server” OnClick=”Button2_Click” Text=”Button2″ />

using System;

public partial class _Default : System.Web.UI.Page
public string message;

protected override void OnInit(EventArgs e)

//Attach event handler for Page Load event.
this.Load += new EventHandler(Page_Load);

//Attache event handler for button1 Click event.
this.Button1.Click += new EventHandler(Button2_Click);

protected void Page_Load(object sender, EventArgs e)
//Displays message when the Page.Load event is fired.
//message = “In the Page_Load event handler.”;

protected void Button1_Click(object sender, EventArgs e)
//Displays message when the button Click event is fired.
message = “In the button1 click event Calling Button2 Click Event ->”;

protected void Button2_Click(object sender, EventArgs e)
message = “In the button2 click event :”;