1

In my C# project, I am creating a Hangman game that has a set of buttons which contains the alphabets from A to Z. All these buttons when clicked will execute the same method. I do not want to create an event handler for each of them one by one. So how do I create a SINGLE event handler for all these buttons?

3 Answers 3

7

Subscribe same handler for all buttons and use sender to get button which raised event:

void Button_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;
    // use Name or Tag of button
}

If your buttons named as alphabets A..Z then you can just use button.Name to get letter. If buttons have names like buttonA...buttonZ you can get substring from button.Name to get related letter (or button.Name.Last()). If buttons have names not related to alphabets, then you can use Tag property of button to set and get letter which is assigned to each button.

Sign up to request clarification or add additional context in comments.

4 Comments

After I did what you told me, there was an error on my error list that said 'Hangman_APPD_Assignment.Form2' does not contain a definition for 'Sbtn_Click' and no extension method 'Sbtn_Click' accepting a first argument of type 'Hangman_APPD_Assignment.Form2' could be found (are you missing a using directive or an assembly reference?)
@user2622438 looks like you had Sbtn_Click method, which was removed, but you still use it to subscribe to event. Go to source of error and remove subscription
Nevermind. The problem is solved. Thanks for your solution! :)
@user2622438 that means you deleted 26 methods definitions, but you still using them in your code. You should remove them manually. I believe you have button names Abtn..Zbtn then you can get letter with button.Name.First() or button.Name.Substring(0,1)
1

Assume you have button1, button2, button3. You can point all the buttons click event to the same method on the design page:

or in the load event

button1.Click+=button_Click;
button2.Click+=button_Click;
button3.Click+=button_Click;

and you write the method

private void button_Click(object sender, EventArgs e)
{
    var button=sender as Button;
    // your code

}

Comments

0

Something like

private void Button_Click(object sender, EventArgs e)
    {
        Button b = (Button) sender;
        //button name
    }

msdn

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.