简体   繁体   中英

C# create an array of controls

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?

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;
    ...
  }
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM