删除动态创建的 PictureBox 时出错

Error in removing a dynamically created PictureBox

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

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

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

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

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 的一半,这很奇怪

请帮帮我

如果需要,下面是我如何动态创建 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 循环中修改集合:

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();
}