博客转载地址:http://www.mzwu.com/article.asp?id=2254
//在panel1中添加20个Button int row = -1; int rowcount = 5; for (int i = 1; i <= 20; i++) { if (i % rowcount == 1) row++; Button button = new Button(); button.Width = 75; button.Height = 23; button.Text = "button" + i.ToString(); button.Top = row * (23 + 2); button.Left = ((i-1) % rowcount) * (75 + 2); panel1.Controls.Add(button); }
使用foreach+Control.Controls移除所有Button:
foreach (Control con in panel1.Controls) panel1.Controls.Remove(con);
结果发现只移除了10个,界面还剩下10个!改用for循环:
for (int i = 0; i < panel1.Controls.Count; i++) panel1.Controls.RemoveAt(i);
结果同上,正确的代码应为:
for (int i = panel1.Controls.Count - 1; i >= 0; i--) panel1.Controls.RemoveAt(i);
究其原因,应是调用Remove或RemoveAt方法时,也改变了Controls内容所致,做个测试:
for (int i = 0; i < panel1.Controls.Count; i++) { textBox1.Text += string.Format("i值:{0}, Controls.Count值:{1}, 移除:{2} ", i, panel1.Controls.Count, panel1.Controls[i].Text); panel1.Controls.RemoveAt(i); }
结果:
i值:0, Controls.Count值:20, 移除:button1 i值:1, Controls.Count值:19, 移除:button3 i值:2, Controls.Count值:18, 移除:button5 i值:3, Controls.Count值:17, 移除:button7 i值:4, Controls.Count值:16, 移除:button9 i值:5, Controls.Count值:15, 移除:button11 i值:6, Controls.Count值:14, 移除:button13 i值:7, Controls.Count值:13, 移除:button15 i值:8, Controls.Count值:12, 移除:button17 i值:9, Controls.Count值:11, 移除:button19
测试发现:移除子控件应尽量用Remove或RemoveAt方法,若使用Clear方法,在多次动态添加/移除控件后,程序占用内存越来越高,估计是Clear没有及时释放资源所致。
......