我在应该创建24个动态创建的对象的方法中有一个while循环。但是,循环将创建3,然后停止。
int test = 24;
while (placenum< test)
{
FlowLayoutPanel name = new FlowLayoutPanel();
FlowLayoutPanel data = new FlowLayoutPanel();
FlowLayoutPanel pic = new FlowLayoutPanel();
int sort = 0;
while (sort == 0)
{
SearchR.Searchrdata.Controls.Add(first);
first.Margin = new Padding(50, 50, 3, 50);
first.Size = new Size(320, 320);
first.BackColor = Color.Azure;
first.Controls.Add(name);
name.Size = new Size(320, 22);
name.Margin = new Padding(0);
first.Controls.Add(data);
data.Size = new Size(320, 22);
data.Margin = new Padding(0);
first.Controls.Add(pic);
pic.Size = new Size(320, 276);
pic.Margin = new Padding(0);
sort = 1;
placenum = placenum + 1;
}
while (sort == 1)
{
SearchR.Searchrdata.Controls.Add(two);
two.Margin = new Padding(0, 50, 3, 50);
two.Size = new Size(320, 320);
two.BackColor = Color.DarkGray;
two.Controls.Add(name);
name.Size = new Size(320, 22);
name.Margin = new Padding(0);
two.Controls.Add(data);
data.Size = new Size(320, 22);
data.Margin = new Padding(0);
two.Controls.Add(pic);
pic.Size = new Size(320, 276);
pic.Margin = new Padding(0);
sort = 2;
placenum = placenum + 1;
}
while (sort == 2)
{
SearchR.Searchrdata.Controls.Add(last);
last.Margin = new Padding(0, 50, 10, 50);
last.Size = new Size(320, 320);
last.BackColor = Color.Bisque;
last.Controls.Add(name);
name.Size = new Size(320, 22);
name.Margin = new Padding(0);
last.Controls.Add(data);
data.Size = new Size(320, 22);
data.Margin = new Padding(0);
last.Controls.Add(pic);
pic.Size = new Size(320, 276);
pic.Margin = new Padding(0);
sort = 0;
placenum = placenum + 1;
}
};
return null;
称为
FlowLayoutPanel
的Searchrdata
是应该创建其他对象的那个,但它仅生成3个并停止。最佳答案
您有三个名为first
,two
和last
的变量。大概是您要添加的控件。问题是您要一遍又一遍地添加三个变量的相同实例。如果要每次添加一个新实例,则应该每次创建一个新的first
,two
和last
实例。请注意,您已经使用name
,data
和pic
执行此操作。
另外,正如其他人所指出的,您也不需要while (sort == 1)
它应该是if (sort == 1)
。
最后,请注意,如果您通过调试器运行代码并逐步执行,您会发现循环正在运行所需的次数,并且您可能已经弄清楚了真正的问题是什么。
关于c# - While循环仅创建3个对象不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39150134/