6

Is it possible to create an array of controls? Is there a way to get the index of a control if more than one of the controls in the array share the same event handler?

4
  • Please, define components. Maybe a code sample would help. Commented Jan 30, 2010 at 15:35
  • for example: I want to have 30 buttons on a form that share the same click event Commented Jan 30, 2010 at 15:42
  • The sender parameter of the click event will be the button that generated the click, so getting the index would be Array.IndexOf(buttonArray, sender) Commented Jan 30, 2010 at 15:48
  • Wouldn't referencing the Microsoft.VisualBasic namespace do as it has the means to use a controls array? Commented Jan 30, 2010 at 15:55

2 Answers 2

8

This is certainly possible to do. Sharing the event handler is fairly easy to do in this case because the Button which raised the event is sent as part of the event args. It will be the sender value and can be cast back to a Button

Here is some sample code

class Form1 : Form {
  private Button[] _buttons;
  public Form1(int count) { 
    _buttons = new Button[count];
    for ( int i = 0; i < count; i++ ) {
      var b = new Button();
      b.Text = "Button" + i.ToString()
      b.Click += new EventHandler(OnButtonClick);
      _buttons[i] = b;
    }
  }
  private void OnButtonClick(object sender, EventArgs e) {
    var whichButton = (Button)sender;
    ...
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

this solution works for me. it's exactly what i was looking for.
4

Based on Kevins comment:

foreach(Button b in MyForm.Controls.OfType<Button>())
{
    b.Click += Button_Click;
}

void Button_Click(object sender, EventArgs e)
{
    Button clickedButton = sender as Button;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.