views:

96

answers:

6

I have 6 buttons that I want to be attached to the same handler. How can I do this?

+7  A: 

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
}
hunter
+5  A: 

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.

Reed Copsey
+1 over hunter's answer for the explanation.
KeithS
aww, come on... doesn't this guy have enough points? ;P
hunter
@hunter: I did vote your answer up, at least ;)
Reed Copsey
+3  A: 

How to see which button was pressed:

Use the sender

Button myButton = (Button)sender;

sender is a parameter of type object in your event handler.

Alexander
A: 

Instead of double clicking the event in the designer you can paste the name of the event handler to to the event in the designer property grid.

Itay
+2  A: 

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.

hmemcpy
A: 
myButton1.Click += new EventHandler(MyButtonClick);
myButton2.Click += new EventHandler(MyButtonClick);
myButton3.Click += new EventHandler(MyButtonClick);
myButton4.Click += new EventHandler(MyButtonClick);
myButton5.Click += new EventHandler(MyButtonClick);
myButton6.Click += new EventHandler(MyButtonClick);

public void MyButtonClick(object sender, MouseButtonEventArgs e)
{
                switch ((sender as Button).Name)
                {
                case "button1":
                    //actions
                    break;
                case "button2":
                    //actions
                    break;
                default:
                    break;
               }
}
Tokk