Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使5x5按钮数组中的每个按钮/复选框具有不同的事件处理程序?_C#_Winforms_Eventhandler - Fatal编程技术网

C# 如何使5x5按钮数组中的每个按钮/复选框具有不同的事件处理程序?

C# 如何使5x5按钮数组中的每个按钮/复选框具有不同的事件处理程序?,c#,winforms,eventhandler,C#,Winforms,Eventhandler,我有这段代码 public void initButtons(CheckBox[,] buttons) { int locX = 0; int locY = 0; for(int x = 0; x < buttons.GetLength(0); x++) { for(int y = 0; y < buttons.GetLength(1); y++) {

我有这段代码

public void initButtons(CheckBox[,] buttons)
    {
        int locX = 0;
        int locY = 0;

        for(int x = 0; x < buttons.GetLength(0); x++)
        {
            for(int y = 0; y < buttons.GetLength(1); y++)
            {
                buttons[x, y] = new CheckBox();
                buttons[x, y].Appearance = Appearance.Button;
                buttons[x, y].Location = new Point(locX, locY);
                buttons[x, y].Size = new Size(60, 60);
                buttons[x, y].Click += new EventHandler(this.MemoryButton_Clicked);
                this.Controls.Add(buttons[x, y]);

                locX += 60; 
            }
            locX = 0;
            locY += 60;
        }
    }

…这将创建一个5x5的复选框网格。我希望每个按钮都有一个不同的EventHandler,而不是所有按钮共享同一个。这可能吗?

可以使用lambda表达式将匿名函数作为事件处理程序

buttons[x, y].Click += new EventHandler((s, ea) =>
{
    //insert code here;
});
这样做使用闭包,所以您可以做如下整洁的事情

buttons[x, y].Click += new EventHandler((s, ea) =>
{
    var aString = String.Format("my coordinates are {0} and {1}", x, y);
});

好吧,我把它修好了。基本上我只是添加按钮[x,y].Name=Button+i;和i++;在前循环中。2d数组中的每个元素都有一个唯一的名称,如果我以后想调用它,可以使用.name.Equals


多亏了

为每个按钮创建一个EventHandler数组顺便问一下,这是wpf还是winforms?您可以使用Sender实现此目的,请选中此示例@gogaz这是winforms为什么使用复选框?甚至你的数组也被命名为buttons