简体   繁体   English

按钮数组的Click事件

[英]Click event for a Button Array

I have a Button array in C# WFA and I want to create an event for a click of any button in the array. 我在C#WFA中有一个Button数组,我想为单击数组中的任何按钮创建一个事件。 How can I do it? 我该怎么做? And how to know which location in the array it is? 以及如何知道它在数组中的哪个位置? I know sender is the button itself 我知道发件人是按钮本身

You can use a for loop that closes over a variable containing the current index: 您可以使用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);
}

You can add the event handler to each button in a for loop. 您可以将事件处理程序添加到for循环中的每个按钮。

Inside the handler, you can call array.IndexOf((Button)sender) . 在处理程序内部,可以调用array.IndexOf((Button)sender)

try this 尝试这个

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

    }
}

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

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