【问题标题】:calling function from programmatically created button event [duplicate]从以编程方式创建的按钮事件调用函数[重复]
【发布时间】:2018-05-03 20:28:31
【问题描述】:

我在窗体数据网格视图中有一个二维按钮数组。当用户单击按钮时,我想将按钮的 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 坐标传递给函数。只是想知道我的代码是否有问题?

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    这是因为一个叫做闭包的东西。

    基本上,因为点击事件子方法是在for循环结束后调用的,所以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);
                };
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 1970-01-01
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      相关资源
      最近更新 更多