C# 创建控件数组

C# create an array of controls(C# 创建控件数组)

本文介绍了C# 创建控件数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建控件数组?如果数组中的多个控件共享同一个事件处理程序,有没有办法获取控件的索引?

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?

推荐答案

这当然是可以做到的.在这种情况下,共享事件处理程序相当容易,因为引发事件的 Button 是作为事件参数的一部分发送的.它将是 sender 值,并且可以转换回 Button

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

这里是一些示例代码

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

这篇关于C# 创建控件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# 创建控件数组

基础教程推荐