0

I am trying to draw lots of instances of an image using the following code:

PictureBox[] sprites = new PictureBox[100];

private void Game_Load(object sender, EventArgs e)
{
    PictureBox mainSprite = new PictureBox();
    Bitmap img = new Bitmap(SpriteTest.Properties.Resources.Image); //Load a png image

    mainSprite.Size = new Size(16, 16);
    mainSprite.Image = img;

    for(var i = 0; i < sprites.Length; i++)
    {
        sprites[i] = mainSprite;

        //Keeping it simple for now with a single row of sprites
        sprites[i].Location = new Point(i * 16, 8); 
    }

    Game.ActiveForm.Controls.AddRange(sprites);
}

When it comes to running the code, only the last image is shown. While debugging the code, everything seems to be working as expected. I can also verify that the location is in fact being updated.

I have also tried adding the controls differently using the following code in the for loop (with no luck);

this.Controls.Add(sprites[i]);

I have had this problem many times, especially when I tried to create many GroupBoxes in a similar fashion. For the hours that I searched online as I tried to find a solution, nothing has ever fixed it.

Dulini Atapattu
  • 2,735
  • 8
  • 33
  • 47
AquaGeneral
  • 155
  • 1
  • 19

1 Answers1

6

You're only actually creating one instance of PictureBox:

PictureBox mainSprite = new PictureBox();

...

for(var i = 0; i < sprites.Length; i++)
{
    sprites[i] = mainSprite;

Your array will have lots of reference to the same object. You should create a new PictureBox on each iteration of the loop:

for(var i = 0; i < sprites.Length; i++)
{
    PictureBox mainSprite = new PictureBox();
    mainSprite.Size = new Size(16, 16);
    mainSprite.Image = img;
    sprites[i] = mainSprite;
    ...
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you very much! As a side note, nothing at all was showing up using: Game.ActiveForm.Controls.AddRange(sprites). So I simply added; this.Controls.Add(sprites[i]) and it works perfectly! – AquaGeneral Jul 07 '11 at 07:35