1

我在 C# WFA 中有一个 Button 数组,我想为单击数组中的任何按钮创建一个事件。我该怎么做?以及如何知道它在数组中的哪个位置?我知道发件人是按钮本身

4

3 回答 3

6

您可以使用for关闭包含当前索引的变量的循环:

for(int i = 0; i < buttons.Length; i++)
{
    //it's important to have this; closing over the loop variable would be bad
    int index = i;  
    buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
}
于 2013-11-01T18:24:36.667 回答
3

您可以将事件处理程序添加到 for 循环中的每个按钮。

在处理程序内部,您可以调用array.IndexOf((Button)sender).

于 2013-11-01T18:23:48.240 回答
0

尝试这个

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Button[] myButtons = new Button[10];
        private void Form1_Load(object sender, EventArgs e)
        {

            for(int i = 0; i < myButtons.Length; i++)
            {
                int index = i;
                this.myButtons[i] = new Button();

                this.myButtons[i].Location = new System.Drawing.Point(((i + 1) * 70), 100 + ((i + 10) * 5));
                this.myButtons[i].Name = "button" + (index + 1);
                this.myButtons[i].Size = new System.Drawing.Size(70, 23);
                this.myButtons[i].TabIndex = i;
                this.myButtons[i].Text = "button" + (index + 1);
                this.myButtons[i].UseVisualStyleBackColor = true;
                this.myButtons[i].Visible = true;

                myButtons[i].Click += (sender1, ex) => this.Display(index+1);

                this.Controls.Add(myButtons[i]);
            }
        }

        public void Display(int i)
        {
            MessageBox.Show("Button No " + i);
        }

    }
}
于 2013-11-01T18:36:13.693 回答