Handling multiple button actions in one action in C#

Total Post:154

 1662  View(s)
Rate this:

I have 70 buttons whose names are like button1, button2, button3 and so on. My aim is that whenever button1 is clicked, it will say "1", button2 will say as "2" and so on for the others.

The code for button1 to speak is:

SpeechSynthesizer synthesizer = new SpeechSynthesizer();
private void button1_Click(object sender, EventArgs e)
For button2
private void button2_Click(object sender, EventArgs e)

and so on for other 68 buttons.

Now it is difficult to implement the 70 button's actions. These button actions follow a pattern - so can anyone suggest a more efficient way I can implement these button handlers to save me writing out 70 different actions?

  1. Post:145

    Re: Handling multiple button actions in one action in C#

    Hi Manoj,

    Use same handler for all buttons. Sender of event will be the button which raised event. You can get it's name and extract text to say:

    private void button_Click(object sender, EventArgs e)
        Button button = (Button)sender;
        string text = button.Name.Substring("button".Length);

      Modified On Apr-03-2018 05:51:56 AM