Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# c中控件的不正确复制#_C#_Visual Studio 2008 - Fatal编程技术网

C# c中控件的不正确复制#

C# c中控件的不正确复制#,c#,visual-studio-2008,C#,Visual Studio 2008,为什么此代码不能正常工作: class CTabPage : TabPage CTabPage tp = new CTabPage(); for (int i=0; i < TabControl.TabPages[0].Controls.Count; i++) tp.Controls.Add(TabControlTabControl.TabPages[0].Controls[i]); class-CTabPage:TabPage CTabPage tp=新的CTabPage

为什么此代码不能正常工作:

class CTabPage : TabPage

CTabPage tp = new CTabPage();

for (int i=0; i < TabControl.TabPages[0].Controls.Count; i++)
     tp.Controls.Add(TabControlTabControl.TabPages[0].Controls[i]);
class-CTabPage:TabPage
CTabPage tp=新的CTabPage();
对于(int i=0;i
其中TabControl是现有的TabControl


问题是自从
TabControl.TabPages[0]以来,只复制了一半的控件。controls.Count在循环中递减。

一个控件只能有一个父控件

通过向新的
选项卡页.controls
集合中“添加”控件,您将从旧集合中删除它们,这会导致在迭代
for
循环时
Count
的值减小

要解决您遇到的问题,可以向后迭代:

for (int i=TabControl.TabPages[0].Controls.Count-1; i==0; i--)
    tp.Controls.Add(TabControlTabControl.TabPages[0].Controls[i]);