今天遇到一个奇怪的问题,在WinForm内动态添加Button后再动态的移除,发生稀奇古怪的现象,Button控件只被规律的移除,没有彻底移除html
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(); } } }
移除前的界面ui
移除后的界面this
太诡异了,花费了半天才发现,使用this.Controls遍历时,每删除一个Button后界面的Controls会变化,不会保留上一次的状态,具体缘由尚未搞明白,要想实现全部动态添加的Button都移除掉,使用下列代码spa
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值,而后遍历删除,由于位置是固定的code
效果以下orm
好奇怪的问题,知道具体缘由的大侠请留言htm
参考了园子的大牛blog