Hanumendra
Hanumendra

Reputation: 319

dynamically adding controls under loop in C#

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?

Upvotes: 3

Views: 10300

Answers (3)

Andrei
Andrei

Reputation: 56688

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++)

Upvotes: 4

omer schleifer
omer schleifer

Reputation: 3935

Try this:

private int txtBoxStartPosition = 100;
private int txtBoxStartPositionV = 25;

 for (int i = 0; i < 7; i++)
{
    newLabel = new Label();
    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;


}

Upvotes: 3

Ɖiamond ǤeezeƦ
Ɖiamond ǤeezeƦ

Reputation: 3331

You need to put the line private Label newLabel = new Label(); in the for loop.

private int txtBoxStartPosition = 100;
private int txtBoxStartPositionV = 25;

for (int i = 0; i < 7; i++)
{
    Label newLabel = new Label();
    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;
}

Upvotes: 1

Related Questions