zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    C#发送邮件简单例子
    ABAP随笔
    日期格式转换
    正则校验金额,整数8位,小数3位。
    angular语法运用技巧
    Oracle中连接与加号(+)的使用
    含有代码分析的面试题
    面试的java题目
    递归查询
    本地没有ORACLE远程登录oracle服务器
  • 原文地址:https://www.cnblogs.com/masonlu/p/9322899.html
Copyright © 2011-2022 走看看