Nathan Abramov
Nathan Abramov

Reputation: 115

Changes entire array instead of one cell

I have a 2D array of PictureBox, and I want in a loop to change each picturebox's location and add it to the form, but when I change one cell's property it changes every one of the other cells too. (The constructor gets the form's object and sets it to form variable)

private Form form;
private PictureBox[,] board = new PictureBox[8, 8];
private void PrintBoard()
    {
        for (int i = 0; i < 8; i++)
        {
            for (int j = 0; j < 8; j++)
            {
                board[i, j].Left = j * 20;
                form.Controls.Add(board[i, j]);
            }
        }
    }

Upvotes: 0

Views: 89

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

I think problem is in filling array of picture boxes - you are adding reference to same picture box to all cells. You should create new PictureBox for each cell:

for(int i = 0; i <= board.GetUpperBound(0); i++)
    for (int j = 0; j < board.GetUpperBound(1); j++)
        board[i, j] = new PictureBox(); // create new picture box for each cell

Upvotes: 2

Related Questions