【转载】foreach+Control.Controls无法一次性移除所有子控件解决方法

博客转载地址:http://www.mzwu.com/article.asp?id=2254

//在panel1中添加20个Button
int row = -;
int rowcount = ; for (int i = ; i <= ; i++)
{
if (i % rowcount == )
row++; Button button = new Button();
button.Width = ;
button.Height = ;
button.Text = "button" + i.ToString();
button.Top = row * ( + );
button.Left = ((i-) % rowcount) * ( + ); panel1.Controls.Add(button);
}

使用foreach+Control.Controls移除所有Button:

foreach (Control con in panel1.Controls)
panel1.Controls.Remove(con);

结果发现只移除了10个,界面还剩下10个!改用for循环:

for (int i = ; i < panel1.Controls.Count; i++)
panel1.Controls.RemoveAt(i);

结果同上,正确的代码应为:

for (int i = panel1.Controls.Count - ; i >= ; i--)
panel1.Controls.RemoveAt(i);

究其原因,应是调用Remove或RemoveAt方法时,也改变了Controls内容所致,做个测试:

for (int i = ; i < panel1.Controls.Count; i++)
{
textBox1.Text += string.Format("i值:{0}, Controls.Count值:{1}, 移除:{2}\r\n", i, panel1.Controls.Count, panel1.Controls[i].Text);
panel1.Controls.RemoveAt(i);
}

结果:

i值:, Controls.Count值:, 移除:button1
i值:, Controls.Count值:, 移除:button3
i值:, Controls.Count值:, 移除:button5
i值:, Controls.Count值:, 移除:button7
i值:, Controls.Count值:, 移除:button9
i值:, Controls.Count值:, 移除:button11
i值:, Controls.Count值:, 移除:button13
i值:, Controls.Count值:, 移除:button15
i值:, Controls.Count值:, 移除:button17
i值:, Controls.Count值:, 移除:button19

测试发现:移除子控件应尽量用Remove或RemoveAt方法,若使用Clear方法,在多次动态添加/移除控件后,程序占用内存越来越高,估计是Clear没有及时释放资源所致。 

......

上一篇:pycharm 如何进行全部搜索


下一篇:一起学makefile