If I take some pictureboxes that already exist and add them to an array, Visual Studio is fine with this. I can say, for example, trees[64].BringToFront();
, and it'll bring that picturebox to the front everything's fine.
However, when I use a loop to bring every picturebox in the array to the front from start to finish, it throws an error. Doesn't matter where I start or end, doesn't matter how I do the loop, still gives me the exception.
However, if I use a number instead of an int, even if it's still in the loop, it's fine. I can even tell the for loop to start and end on one arbitrary number and it throws the exception, but if I write the exact same number into the array of pictureboxes (trees[]
) it works fine.
All I want to do is use a loop to bring all the pictureboxes to the front, is that just something that isn't possible?
Also, in case you're wondering why the try/catch
statement looks like that, it's because the pictureboxes are arranged in an 11x11 grid
( TA0, TB0, TC0 ... TA1, TB1, TC1 ... TA2, TB2, TC2 ... . . . . . . . . . )
public partial class Form1 : Form
{
int[] Cell = new int[121];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Generate();
}
private void Generate()
{
var trees = new PictureBox[121];
Random rnd = new Random();
int n;
for (int i = 0; i < 10; i++)
{
try
{
trees[i] = (PictureBox)Controls.Find("TA" + (i).ToString(), true)[0];
trees[i + 11] = (PictureBox)Controls.Find("TB" + (i + 1).ToString(), true)[0];
trees[i + 22] = (PictureBox)Controls.Find("TC" + (i + 1).ToString(), true)[0];
trees[i + 33] = (PictureBox)Controls.Find("TD" + (i + 1).ToString(), true)[0];
trees[i + 44] = (PictureBox)Controls.Find("TE" + (i + 1).ToString(), true)[0];
trees[i + 55] = (PictureBox)Controls.Find("TF" + (i + 1).ToString(), true)[0];
trees[i + 66] = (PictureBox)Controls.Find("TG" + (i + 1).ToString(), true)[0];
trees[i + 77] = (PictureBox)Controls.Find("TH" + (i + 1).ToString(), true)[0];
trees[i + 88] = (PictureBox)Controls.Find("TI" + (i + 1).ToString(), true)[0];
trees[i + 99] = (PictureBox)Controls.Find("TJ" + (i + 1).ToString(), true)[0];
trees[i + 110] = (PictureBox)Controls.Find("TK" + (i + 1).ToString(), true)[0];
}
catch (IndexOutOfRangeException)
{
MessageBox.Show("pictureBox does not exist!");
}
}
for(int idx = 0; idx <= 120; idx++)
{
n = rnd.Next(1, 3);
Cell[idx] = n;
trees[idx].BringToFront();
}
}
}