简体   繁体   English

C#创建一个控件数组

[英]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. 在这种情况下,共享事件处理程序相当容易,因为引发事件的Button是作为事件args的一部分发送的。 It will be the sender value and can be cast back to a Button 它将是sender值,可以转换回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: 基于Kevins评论:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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