0
votes

I have 10 buttons, 0-9 (button0, button1, button2...). When I click any of these buttons, I would like to perform the same routine on them. I would like to know how to, upon clicking of any of these buttons, direct them to the routine below.

    private void button0_Click(object sender, EventArgs e)
    {
        int newValue;

        newValue = Convert.ToInt32(Button.text);
    }

I have already gone into the properties of each button, then events, and changed the click event to button0_Click (I would have thought this would add "handles button1.click, button2.click, etc." after "private void button0_Click(object sender, EventArgs e)" but if it does that in the background, that's ok as long as it works.)

I also need to know how to identify the button that has been pressed, which is where I'm at with "Convert.ToInt32(Button.text)" (e.g. button2.text = "2").

3

3 Answers

2
votes

You can select the same event handler for all the buttons in the designer (in the event tab of the properties window, select the event and there'll be a drop down with all your defined event handlers).

To get which button has been clicked on, cast the sender argument to a Button and you'll have it.

Button button = (Button)sender;
int value = int.Parse( button.Text );

Edit: Also, the "Handles control.event" syntax only exists in Visual Basic.

Edit: Check out the generated code (Form1.Designer.cs, for example) to see how the events are hooked up.

0
votes

The C# language doesn't use handles to bind events (as VB does). The code for the actual binding is in the generated code for the form, i.e. in the background as you put it.

The sender property is a reference to the control where the event happened. You just need to cast it to the actual type of the control:

private void button0_Click(object sender, EventArgs e)
{
    Button button = (Button)sender;
    int newValue = Convert.ToInt32(button.text);
}

As an alternative to using the text of the button (for example if you want to translate the application to different languages, or simply don't want to rely on the text), you can put whatever you like in the Tag property of each button, and retrieve it in the event handler.

0
votes

You could wire them all up to the same event handler an extract the button from sender e.g.

private void button0_Click(object sender, EventArgs e)
{
    var button = sender as Button
    if (button != null)
    {
        int newValue = Convert.ToInt32(Button.text);
    }
}