Search code examples
c#arraysvisual-studiopicturebox

Adding PictureBox into array


I am creating an array of picture boxes however I am unsure of the code needed to put the new picture boxes into the array.

    PictureBox[] bossHealth = new PictureBox[20];
        for( int i = 0; i<19; i++)
        {
            bossHealth[i].Name = "health";
            bossHealth[i].Size = new Size(10, 26);
            bossHealth[i].BackColor = Color.LimeGreen;
            bossHealth[i].Location = new Point(this.Width / 2 + (i * 10), 12);
            bossHealth.Add(bossHealth[i]);
            Controls.Add(bossHealth[i]);
        }

Solution

  • After the code line PictureBox[] bossHealth = new PictureBox[20]; You have an array with room for 20 picture boxes. However, every cell in this array contains null - you must initialize it in your loop.

    Also, this line bossHealth.Add(bossHealth[i]); makes no sense. Arrays does not have an Add method, and bossHealth[i] is already a part of the array. Seems like you are mixing up arrays and lists.

    Here is an improved version of your code:

    PictureBox[] bossHealth = new PictureBox[20];
    for( int i = 0; i<19; i++)
    {
        bossHealth[i] = new PictureBox();
        bossHealth[i].Name = "health";
        bossHealth[i].Size = new Size(10, 26);
        bossHealth[i].BackColor = Color.LimeGreen;
        bossHealth[i].Location = new Point(this.Width / 2 + (i * 10), 12);
        Controls.Add(bossHealth[i]);
    }