0

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]);
            }
        }
    }
4
  • 3
    Where are you getting i from? Commented Jan 3, 2013 at 17:02
  • seems he missed one for loop Commented Jan 3, 2013 at 17:03
  • oops sorry, I did miss the loop Commented Jan 3, 2013 at 17:10
  • @NathanAbramov how do you add picture boxes to board? Commented Jan 3, 2013 at 17:14

1 Answer 1

2

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

5 Comments

And by the way, I use this in the form as a reference of the form object, how can i get the reference without the this, and in another calss?
"the method has some invalid arguments"
@NathanAbramov can you post code which you have problems with?
class a{ Game game = new Game(this); } Im creating a new instance of the Game object from a calss, and i cant use this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.