删除动态创建的PictureBox

时间:2018-07-17 08:58:06

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

我正在使用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++;
        }
    }
}

在此之前,谢谢:)

1 个答案:

答案 0 :(得分:0)

尝试执行此操作以避免在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();
}