[C#]WinForm动态删除控件 Controls.Remove()

今天遇到一个奇怪的问题,在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

原文地址:https://www.cnblogs.com/masonlu/p/9322899.html