今天遇到一個奇怪的問題,在WinForm內動態添加Button后再動態的移除,發生稀奇古怪的現象,Button控件只被規律的移除,沒有完全移除
foreach (Control c in this.Controls) { if (c is Button && ((Button)c).ForeColor == Color.White) { this.Controls.Remove(c); c.Dispose(); } if (c is Label && c.Tag != null) { if (((Label)c).Tag.ToString().Equals("Col") || ((Label)c).Tag.ToString().Equals("Row")) { Text += "|" + c.Name; //Controls.Remove(c); //c.Dispose(); } } }
移除前的界面
移除后的界面
太詭異了,花費了半天才發現,使用this.Controls遍歷時,每刪除一個Button后界面的Controls會變化,不會保留上一次的狀態,具體原因還沒有搞明白,要想實現所有動態添加的Button都移除掉,使用下列代碼
List<int> lstPoint = new List<int>() { 160, 235, 310, 385, 460, 535, 125 }; for (int i = this.Controls.Count - 1; i >= 0; i--) { if (lstPoint.Contains(Controls[i].Location.Y) || Controls[i].Location.X == 20) { this.Controls.RemoveAt(i); } }
先記錄每行的坐標的Y值,然后遍歷刪除,因為位置是固定的
效果如下
好奇怪的問題,知道具體原因的大俠請留言
參考了園子的大牛
https://www.cnblogs.com/yuzhihui/p/5749233.html