用循环遍历窗体中的控件十分简单:
假设存在Form1,Form2;
Form1中存在一个BUTTON1
Form2中存在两个控件,一个LABEL1,一个BUTTON1以下是BUTTON1的CLICK事件
Form2 frmTarget=new Form2();
foreach (Control ctl in frmTarget.Controls)
{
  MessageBox.Show(ctl.Text);
}结果运行正常,MESSAGEBOX显示两次,“Button1”和“Label1”但是,如果执行以下代码:
foreach (Control ctl in frmTarget.Controls)
{
  this.Controls.Add(ctl);
  MessageBox.Show(ctl.Text);
}
MessageBox只显示一次,“Button1”,同时窗体中也只添加了Button1这个控件。为了解决这个问题,我不得不添加一个List<Control>来暂时存放控件信息。Form2 frmTarget = new Form2();
List<Control> ctlCol = new List<Control>();
foreach (Control ctl in frmTarget.Controls)
{
  ctlCol.Add(ctl);
}
foreach (Control ctl in ctlCol)
{
  this.Controls.Add(ctl);
}
问题是解决了,但是这代码看着就另人不爽,请教大虾们,这是什么原因导致的?有没有更加好的方法?

解决方案 »

  1.   

    你这个需求真怪异,不过试了一下确实想你说的。执行this.Controls.Add(ctl); 以后frmTarget.Controls的控件就会少一个,不知道原因。不过你可以这样写for(int i=0; i<=frmTarget.Controls.Count; ++i) 

      this.Controls.Add(frmTarget.Controls[0]);   

      

  2.   

    我不是大虾   但是  代码我稍微看明白了一点
    原因应该在  this.Controls.Add(ctl); 
    这条语句上   因为你将ctl添加到了controls 中   然后controls 应该有一个自己刷新的操作
    这样  你的foreach 循环就被终止了
    可以将你的上面的代码改成这样for (int i=0;i<frmTarget.Controls.Count;.i++) 

      this.Controls.Add(frmTarget.Controls[i]); 
      MessageBox.Show(frmTarget.Controls[i].Text); 
    } 这样就应该可以了我是小菜鸟!   说的不好清见谅,   希望能够帮到你!
      

  3.   

    你这样不行,this.Controls.Add(frmTarget.Controls[i]); 以后frmTarget.Controls变少了。所以你这段代码还是只有一个控件
      

  4.   

    这个问题的原因很简单..楼主把foreach (Control ctl in frmTarget.Controls)前加一个frmTarget.Show()就明白了foreach的时候还有两个控件,你把一个加到Form1了,frmTarget.Controls里的控件就少了一个,当然循环条件不满足,直接退出了
      

  5.   

    我想问问这位朋友,为什么窗体A添加窗体B的控件后,控件会从B窗体中移除
      

  6.   

    一个对象实体只能属于一个parent.
      

  7.   

    这样不行,还是只能添加一个控件。根据你思路,稍微改了下:
    int iCount = frmTarget.Controls.Count;
    for (int i = 0; i < iCount; i++)
      this.Controls.Add(frmTarget.Controls[0]);
    就好了。