views:

760

answers:

4

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!

+3  A: 

When specifying the event handler, you can register the same function to handle multiple events (if in VS.Net, go to properties, select the events section (lightning button), click on the drop down for Click). This way you will write one event handler function to handle all the buttons.

Example (C#) if button creation and event registration are done in code:

public void digitButtons_Click(object sender, EventArgs eventArgs) {
    if(sender is Button) {
        string digit = (sender as Button).Text;
        // TODO: do magic
    }
}

public void createButtons() {
    for(int i = 0; i < 10; i++) {
        Button button = new Button();
        button.Text = i.ToString();
        button.Click += digitButtons_Click;
        // TODO: add button to Form
    }
}
earlNameless
+1: Clearly beat me to it...and I like the createButtons too. Of course it relies on the layout manager to do a good job, though.
lc
Yeah, I had to explain that in one of the comments to the original author's post below.
earlNameless
A: 

That is exactly what I was looking for. Thanks a ton!

Nick
You can mark a question as the accepted answer so it shows up differently.
earlNameless
Sorry, an answer as the accepted answer.
earlNameless
+6  A: 

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;
}
lc
+1 for use of Control.Tag, which is much safer than the hack with Text. I was thinking of localization issues in particular.
Wim Coenen
A: 

One more thing. Anyway to group the digit buttons so they can be differentiated from other buttons on the form?

Thanks again.

Nick
You should have made this a separate question.Yes, use create a container with flow layout; create Button[] digitButtons; as a member of the form, store the buttons there, and add them to the flow layout container.
earlNameless