1

I have a two dimensional array of buttons in a windows form data grid view. When the user clicks the button, I want to pass the x,y position of the button to a function to perform another task. At the moment, I'm using this code which runs on form load:

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

however, every time I click on a button in the form, it always pass 8 as x,y coordinates to the function. Just wondering whether there is anything wrong with my code?.

Alexey Subach
  • 11,903
  • 7
  • 34
  • 60
Andrew Neate
  • 109
  • 1
  • 9

1 Answers1

4

This is because of something called closure.

Basically, because the click event sub-method is called after the for loop has finished, the x and y variables are both 8.

Try this:

    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);
            };
        }
    }
jag
  • 517
  • 6
  • 16