删除控件时,发现并不能完全删除所有二维码,原因是每遍历删除一次,整个Control 会发生变化,没有遍历删除完所有二维码
foreach (Control ctrl in this.Controls)
{
if (ctrl is BarCodeControl)
{
BarCodeControl bar = (BarCodeControl)ctrl;
this.Controls.Remove(bar);
}
}
解决办法
ArrayList ALx = new ArrayList();
ArrayList ALy = new ArrayList();
//int index = this.Controls.GetChildIndex((Control)BarCodeControl);
foreach (Control ctrl in this.Controls)
{
if (ctrl is BarCodeControl)
{
BarCodeControl bar = (BarCodeControl)ctrl;
//遍历到二维码时,记录一下位置
ALx.Add(bar.Location.X);
ALy.Add(bar.Location.Y);
i = i + 1;
}
}
//遍历到二维码的位置再删除
for (int j = this.Controls.Count - 1; j >= 0; j--)
{
if (ALy.Contains(Controls[j].Location.Y) || ALx.Contains(Controls[j].Location.X))
{
this.Controls.RemoveAt(j);
}
}