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?.

0

1 Answer 1

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);
            };
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.