How to use single event for multiple controls to do different tasks.

This C# code shows you how to use single event for multiple controls to do diferent task for corresponding control in your ASP.NET application.

Here I am using 3 asp Button Control(Button1, Button2, Button3). The "Text" property of those three are "Kolkata", "Delhi" and "Mumbai". But all those three button have single "onClick" event that is "Button_Click". But their task is different when they are clicked. That means when Button1 is clicked it will fire the Button_Click event and do some task. when Button2 is clicked it also fire the same event that is Button_Click but it do other task not the task that other two button do.

And the Button_Click event Code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)

protected void Button_Click(object sender, EventArgs e)
Button ClickedBtn = (Button)sender;
Response.Write("You Have Clicked on: " + ClickedBtn.Text + ". ");

if (ClickedBtn.ID == "Button1")
Response.Write(ClickedBtn.Text + " is in West Bengal!");
else if (ClickedBtn.ID == "Button2")
Response.Write(ClickedBtn.Text + " is the capital of India!");
Response.Write(ClickedBtn.Text + " is in Maharashtra!");


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: