【问题标题】:Error in removing a dynamically created PictureBox删除动态创建的 PictureBox 时出错
【发布时间】:2018-07-17 17:06:00
【问题描述】:

我正在使用 C# 创建一个纸牌游戏程序,当我想删除每一个代表手牌的 PictureBox 时,突然发生了这件事 每当我添加 this.Controls.Remove(pb)pb.Dispose() 时,Visual Studio 都不会读取控件中的所有 PictureBox,这很奇怪......

这是我不使用 dispose 代码行时的代码和输出:

private void removeCiH(string target)
{
    foreach (PictureBox pb in this.Controls.OfType<PictureBox>())
    {
        Console.WriteLine(pb.Name);
        string x = pb.Name;
        //this.Controls.Remove(pb);
        //pb.Dispose();
    }
}

输出:

p0

p1

p2

p3

p4

p5

这是我使用 dispose 行代码时的代码和输出:

private void removeCiH(string target)
{
    foreach (PictureBox pb in this.Controls.OfType<PictureBox>())
    {
        Console.WriteLine(pb.Name);
        string x = pb.Name;
        this.Controls.Remove(pb);
        pb.Dispose();
    }
}

输出:

p0

p2

p4

当我使用 Dispose 时,VS 不会读取 PictureBox 的一半,这很奇怪

请帮帮我

如果需要,这里是我动态创建图片框的方法

private void paintCiH(PlayerCards _pc, string target)
{
    int x, y, c;
    x = 156;
    c = 0;
    if (target == "p")
    {
        y = 420;
        foreach (Card card in _pc.CiH)
        {
            var newPict = new PictureBox
            {
                Name = target + c,
                Size = new Size(81, 121),
                Location = new Point(x + ((328 / 6) * c), y),
                BackgroundImage = Image.FromFile("img//card_front.png"),
                Image = Image.FromFile("img//Cards//" + card.img)
            };
            //Add it to the event handler and  form
            newPict.Click += new EventHandler(this.card_Click);
            this.Controls.Add(newPict);
            c++;
        }
    }
    else
    {
        y = -99;
        foreach (Card card in _pc.CiH)
        {
            var newPict = new PictureBox
            {
                Name = target + c,
                Size = new Size(81, 121),
                Location = new Point(x + ((328 / 6) * c), y),
                BackgroundImage = Image.FromFile("//img//card_back.png")
            };
            //Add it to the event handler and  form
            newPict.Click += new EventHandler(this.card_Click);
            this.Controls.Add(newPict);
            c++;
        }
    }
}

谢谢,在那之前:)

【问题讨论】:

  • 这是因为当你从父级移除一个控件时,控件的总数越来越少,因此循环也是如此。尝试在循环中放置一个计数器。
  • foreach 正在迭代您的控件列表,并且您可以看到它删除了第一项,因为迭代器位于第一位。然后它移动到下一个。但是您删除了第一个项目,因此第二个项目现在是您最初的第三个项目 p2 如果它删除了它,它会继续前进......但让我想知道的是,在迭代时更改集合时您没有遇到异常。如果您从最后一项开始迭代到第一项,您应该能够解决此问题。
  • 哦,哇,我真的没想到会发生这种情况,谢谢大家

标签: c# runtime-error picturebox dynamically-generated


【解决方案1】:

尝试这样做以避免在foreach循环中修改集合:

var controlsToRemove = this.Controls.OfType<PictureBox>().ToArray();

foreach (PictureBox pb in controlsToRemove)
{
    Console.WriteLine(pb.Name);
    string x = pb.Name;
    this.Controls.Remove(pb);
    pb.Dispose();
}

【讨论】:

  • 谢谢,它正在工作!一直在自己解决它,我什至不认为这是一个迭代问题再次感谢您
猜你喜欢
  • 1970-01-01
  • 2019-02-28
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 2018-12-22
  • 1970-01-01
  • 2013-07-28
相关资源
最近更新 更多