C# – dynamically adding controls under loop in C#

.netc++linqwinforms

I am developing a windows application where I want to create some controls dynamically inside a loop.
The code I am trying is

private Label newLabel = new Label();
private int txtBoxStartPosition = 100;
private int txtBoxStartPositionV = 25;

 for (int i = 0; i < 7; i++)
{

    newLabel.Location = new System.Drawing.Point(txtBoxStartPosition, txtBoxStartPositionV);
    newLabel.Size = new System.Drawing.Size(70, 40);
    newLabel.Text = i.ToString();

    panel1.Controls.Add(newLabel);
    txtBoxStartPositionV += 30;


}

This code is generating only one Label with text 7 but I want to create 8 Lables with their respective texts, how can I do this?

Best Solution

In your loop you are essentially updating properties of the very same Label. If you want create a new one on each step, move creation of the object inside the loop:

private Label newLabel;

for (int i = 0; i < 7; i++)
{
    newLabel = new Label();
    ...

By the way if you want 8 labels - your for should iterate 8 times, not 7, as it does now:

for (int i = 0; i < 8; i++)