用循环遍历窗体中的控件十分简单:
假设存在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);
}
问题是解决了,但是这代码看着就另人不爽,请教大虾们,这是什么原因导致的?有没有更加好的方法?
假设存在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);
}
问题是解决了,但是这代码看着就另人不爽,请教大虾们,这是什么原因导致的?有没有更加好的方法?
{
this.Controls.Add(frmTarget.Controls[0]);
}
原因应该在 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);
} 这样就应该可以了我是小菜鸟! 说的不好清见谅, 希望能够帮到你!
int iCount = frmTarget.Controls.Count;
for (int i = 0; i < iCount; i++)
this.Controls.Add(frmTarget.Controls[0]);
就好了。