从以编程方式创建的按钮事件调用函数

时间:2017-11-20 15:07:49

标签: c# winforms

我在Windows窗体数据网格视图中有一个二维数组的按钮。当用户单击按钮时,我想将按钮的x,y位置传递给执行其他任务的函数。目前,我正在使用在表单加载上运行的代码:

for (int x = 0; x < 8; x++)
{
    for (int y = 0; y < 8; y++)
    {
        BoardButtons[x, y] = new Button();
        Controls.Add(BoardButtons[x, y]);
        BoardButtons[x, y].Visible = true;
        BoardButtons[x, y].Click += (s, ev) =>
        {
            MyFunction(x, y);
        };
    }
}

但是,每次单击表单中的按钮时,它总是将8作为x,y坐标传递给函数。只是想知道我的代码是否有问题?。

1 个答案:

答案 0 :(得分:4)

这是因为闭包。

基本上,因为在for循环结束后调用了click事件子方法,所以x和y变量都是8。

试试这个:

    for (int x = 0; x < 8; x++)
    {
        for (int y = 0; y < 8; y++)
        {
            BoardButtons[x, y] = new Button();
            Controls.Add(BoardButtons[x, y]);
            BoardButtons[x, y].Visible = true;
            int tmpX = x;
            int tmpY = y;
            BoardButtons[x, y].Click += (s, ev) =>
            {
                MyFunction(tmpX, tmpY);
            };
        }
    }
相关问题