Ajay Varghese Ajay Varghese - 3 months ago 10
C# Question

While Loop Not working only creating 3 objects

I have a while loop inside a method that is supposed to create 24 dynamically created objects. However the loop creates 3 and then stops.

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;


the FlowLayoutPanel called Searchrdata is the one that the other objects are supposed to be made but, it makes only 3 and stops.
output

Answer

You have three variables named first, two, and last. Presumably these are the controls you are trying to add. The issue is you are adding the same instance of the three variables over and over again. You should be creating a new instance of first, two, and last each time if you want a new one added each time. Note that you are already doing this with name, data, and pic.

Also, as others have noted, you also don't need while (sort == 1) it should be if (sort == 1).

Finally, note that if you ran your code through the debugger and stepped through, you would see that your loop is running the number of times you want, and you might have figured out what the real issue is.