-1

I have a method which removes all old pictures from an array and add new, but it throws a System.NullReferenceException on the last line.

PictureBox[] selectedCards = new PictureBox[0];
byte selectedCardsCount = 0;
int selectedCardsIndex = 0;

private void AddSelectedCard(int index, PictureBox newCard)
        {
            if (selectedCards.Length != 0)
            {
                foreach (PictureBox card in selectedCards)
                {
                    this.Controls.Remove(card);
                }
            }

            selectedCardsCount++;

            selectedCards = new PictureBox[selectedCardsCount];

            selectedCards[selectedCardsIndex].Image = new Bitmap(newCard.Image); //The exception is thrown on this line

            selectedCardsIndex++;
    }

When i debug the program:

selectedCards[selectedCardsIndex] is 0 (not null)

newCard.Image is System.Drawing.Bitmap (also not null)

  • Your last paragraph does not make sense. `selectedCards[selectedCardsIndex]` is of type `PictureBox`, it can never be `0`. – René Vogt Dec 19 '15 at 13:16

1 Answers1

2

You create a new array of PictureBoxes in this line

selectedCards = new PictureBox[selectedCardsCount];

But this only creates the array, not the PictureBox themselves. So you need to create them:

selectedCards[selectedCardsIndex] = new PictureBox();
this.Controls.Add(selectedCards[selectedCardsIndex]);

selectedCards[selectedCardsIndex].Image = new Bitmap(newCard.Image); 
René Vogt
  • 43,056
  • 14
  • 77
  • 99