foreach (Control c in this.Controls)
            {
                if (c is CheckBox)
                {
                    this.Controls.Remove(c);
                }
            }
我是动态生成多个checkbox,好比生成了10个,然后我想删除这些checkbox,就用上面的方法,可是每次执行这个方法,都不能完全删除这10个checkbox,只能删除3,4个,然后再执行,它再删除3,4个,这是为什么??

解决方案 »

  1.   

    foreach (Control c in this.Controls)
    执行时,不能改变Controls的大小,你在循环中Remove会让Controls变小
    你可以这样:
    List<Control> list=new List<Control>();
    foreach (Control c in this.Controls)
      {
      if (c is CheckBox)
      {
          list.Add(c);
      }
      }
    foreach(Control c in list)
    {
    this.Controls.Remove(c);
    }
      

  2.   

    因为你修改了Controls。
    try thisList<CheckBox> checkboxList = new List<CheckBox>();
    foreach (Control c in Controls)
    {
        if (c is CheckBox) checkboxList.Add(c as CheckBox);
    }
    foreach (CheckBox c in checkboxList)
    {
        Controls.Remove(c);
    }
      

  3.   

    如果.net 3.5以上,支持Linq。可以用Linq简化写法:
    this.Controls.Cast<Control>().Where(c=>c is CheckBox).ToList().ForEach(c => Controls.Remove(c));