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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With