3

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?

3 Answers 3

4

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++)
Sign up to request clarification or add additional context in comments.

Comments

3

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;


}

Comments

1

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;
}

2 Comments

Remove private from the line as per the example.
You didn't say that to begin with ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.