【发布时间】: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