【求助】控件循环遍历,添加的问题!!!
用循环遍历窗体中的控件十分简单:
假设存在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);
}
问题是解决了,但是这代码看着就另人不爽,请教大虾们,这是什么原因导致的?有没有更加好的方法?