代码如下
/// <summary>
/// 清除控件groupBox3
/// </summary>
private void RemoveControl()
{
foreach (Control c in this.groupBox3.Controls)
{
if (c is Label)
{
this.groupBox3.Controls.Remove(c);//删除指定控件
}
}
foreach (Control c in this.groupBox3.Controls)
{
if (c is PictureBox)
{
this.groupBox3.Controls.Remove(c);//删除指定控件
}
}
}
groupBox3里的控件都是动态生成的。有PictureBox和Lable。每次清除都清除的不干净。执行几次清除才能清除完。
求解这是什么原因造成的???
Winform程序
------解决思路----------------------
在foreach循环中更改groupBox3.Controls集合后就不能再继续遍历了,所以你的代码只能删除第一个符合条件的控件
------解决思路----------------------
不要在遍历panel的时候删除panel里的东西
这会造成panel.Controls的数量变化,导致无法遍历完整
你应该先遍历一次,把里面的item放到list里
然后再遍历list删除panel里的item
------解决思路----------------------
别用foreach,用for,从后往前删,否则每次删一个,数量就发生变化了,索引会有问题
for(i=100;i>=0;i--)
------解决思路----------------------
你可以这样写
for (var i=this.groupBox3.Controls.count-1; i>=0 ; i--))
{
Control c= this.groupBox3.Controls[i];
if (c is Label
------解决思路----------------------
c is c is PictureBox)
this.groupBox3.Controls.Remove(c);
}