asp.net How to get the id of the button user clicked

When you use a button clicked event, the signature of the method that'll handle the event goes like this:

protected void foo (object sender, EventArgs e)

sender in this case is the button that was clicked. Just cast it to Button again and there you have it. Like this:

Button button = (Button)sender;
string buttonId = button.ID;

You can have all your buttons pointing their Click event to the same method like this.


The first parameter of your event handler (object source or sometimes object sender) is a reference to the button that was clicked. All you need to do is cast it and then you can retrieve the id value, e.g.:

void Button_Click(object sender, EventArgs e)
{
    Button button = sender as Button;
    if (button != null)
    {
       //get the id here
    }
}

Tags:

Asp.Net