How can I subscribe multiple buttons to the same event handler and act according to what button was clicked?
You can attach the same event to multiple buttons by binding the same method to each buttons click event
myButton1.Click += new MyButtonClick;
myButton2.Click += new MyButtonClick;
myButton3.Click += new MyButtonClick;
myButton4.Click += new MyButtonClick;
myButton5.Click += new MyButtonClick;
myButton6.Click += new MyButtonClick;
void MyButtonClick(object sender, EventArgs e)
{
Button button = sender as Button;
//here you can check which button was clicked by the sender
}
When you subscribe to the event on a button, it's just a standard event handler:
button1.Click += myEventHandler;
You can use the same code to add handlers for every button:
button1.Click += myEventHandler;
button2.Click += myEventHandler;
button3.Click += myEventHandler;
button4.Click += myEventHandler;
button5.Click += myEventHandler;
button6.Click += myEventHandler;
This will cause your handler in myEventHandler
to be run when any of the buttons are clicked.
Just wire the buttons to the same event:
myButton1.Click += Button_Click;
myButton2.Click += Button_Click;
myButton3.Click += Button_Click;
...
And handle the buttons accordingly:
private void Button_Click(object sender, EventArgs e)
{
string buttonText = ((Button)sender).Text;
switch (buttonText)
{
...
}
}
The sender
object contains the reference to the button which caused the Click event. You can cast it back to Button
, and access whatever property you need to distinguish the actual button.