Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create a grid of pictureboxes in an array for a board in c#

I'm trying to make a board for a Naughts and crosses (tic tac toe) game using pictureboxes in an array and what I've come up with is this. This starts when I press a button.

for (int i = 0; i <= 3; i++)
        {
            for (int j = 0; j <= 3; j++)
            {
                PictureBox[,] pb = new PictureBox[i, j];
                pb[i, j].Location = new Point(i * 150 + 100, j * 150 + 100);
                pb[i, j].Width = 150;
                pb[i, j].Height = 150;
                pb[i, j].Visible = true;
                pb[i, j].BorderStyle = BorderStyle.FixedSingle;
                pb[i, j].BringToFront();
                this.Controls.Add(pb[i, j]);
            }
        }

this throws me a "System.IndexOutOfRangeException" on the line

pb[i, j].Location = new Point(i * 150 + 100, j * 150 + 100);

Whats wrong here?

like image 252
Kieran Manson Avatar asked Dec 06 '25 02:12

Kieran Manson


1 Answers

You're not far off - you need to declare the array outside of the loop, and create a picture with each iteration - this works (tested):

            PictureBox[,] pb = new PictureBox[3, 3];
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    pb[i,j] = new PictureBox();
                    pb[i, j].Location = new Point(i * 150 + 100, j * 150 + 100);
                    pb[i, j].Width = 150;
                    pb[i, j].Height = 150;
                    pb[i, j].Visible = true;
                    pb[i, j].BorderStyle = BorderStyle.FixedSingle;
                    pb[i, j].BringToFront();
                    this.Controls.Add(pb[i, j]);
                }
            }

(Note the logic in the loop was wrong too, it should be < 3 not <= 3 as you're starting at 0)

like image 174
NDJ Avatar answered Dec 08 '25 16:12

NDJ