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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With