Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Win Form Calculator: Buttons 0 - 9 Event handler to perform repetitive task

I have a win form UI that looks like a typical calculator. Naturally I do not want to rewrite the same logic for every single numeric button(0-9). I want to be able to know which button was clicked so I can perform calculations based on it's text property. Should I just make a method that accepts the button object as a parameter to promote code reuse? Is there a better way? I would like to hear how more tenured Win Form app devs would handle this. I am attempting to keep my logic out of the UI.

Thanks!

like image 924
Nick Avatar asked Dec 30 '22 06:12

Nick


1 Answers

The typical signature of an event handler is void EventHandler(object sender, EventArgs e). The important part there is the object sender. This is the object that fired the event. In the case of a Button's click event, the sender will be that Button.

void digitButton_Click(object sender, EventArgs e)
{
    Button ButtonThatWasPushed = (Button)sender;
    string ButtonText = ButtonThatWasPushed.Text; //the button's Text
    //do something

    //If you store the button's numeric value in it's Tag property
    //things become even easier.
    int ButtonValue = (int)ButtonThatWasPushed.Tag;
}
like image 56
lc. Avatar answered Jan 01 '23 18:01

lc.