HANDLING MULTIPLE BUTTON ACTIONS IN ONE ACTION IN C#

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
C# 
C#
 1255  View(s)
Ratings:
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)

{

    synthesizer.Speak("1");

}

For button2

private void button2_Click(object sender, EventArgs e)

{

    synthesizer.Speak("2");

}

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. ezra heywood

    Post:145

    Points:1019
    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);

        synthesizer.Speak(text);

    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!