【问题标题】:c# PictureBox always throws NullReferenceException [duplicate]c# PictureBox 总是抛出 NullReferenceException [重复]
【发布时间】:2015-12-19 13:09:23
【问题描述】:

我有一个方法可以从数组中删除所有旧图片并添加新图片,但它会在最后一行抛出 System.NullReferenceException。

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++;
    }

当我调试程序时:

selectedCards[selectedCardsIndex] 为 0(非空)

newCard.Image 是 System.Drawing.Bitmap(也不为空)

【问题讨论】:

  • 你的最后一段没有意义。 selectedCards[selectedCardsIndex] 的类型是 PictureBox,它永远不可能是 0

标签: c# exception picturebox throw


【解决方案1】:

您在这一行中创建了一个新的PictureBoxes 数组

selectedCards = new PictureBox[selectedCardsCount];

但这只会创建数组,而不是 PictureBox 本身。所以你需要创建它们:

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

selectedCards[selectedCardsIndex].Image = new Bitmap(newCard.Image); 

【讨论】:

  • 谢谢,这对我有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-30
  • 2013-05-30
  • 2020-11-17
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多