rzaaeeff
rzaaeeff

Reputation: 880

Dynamically added labels disappear in runtime

I add labels to my form programmatically, but they disappear, except last one. I'm sure that given location to them is appropriate. But when the second label appears, first disappears, or when third label appears, second disappears.

Here is my code:

Label[] lenlab = new Label[255];

Label lab = new Label();
lab.Font = new Font("Microsoft Sans Serif", 10, FontStyle.Bold);
lab.ForeColor = Color.White;
lab.BackColor = Color.Transparent;
lab.AutoSize = true;

lenlab[1] = lab;
lenlab[1].Location = new Point(50, panel1.Location.Y + panel1.Height + 20);
lenlab[1].Text = c[1];
this.Controls.Add(lenlab[1]);

for (int i = 2; i < c.Count; i++) 
{
    lenlab[i] = lab;
    lenlab[i].Location = new Point(lenlab[i - 1].Location.X + lenlab[i -1].Width + 40, lenlab[i - 1].Location.Y);
    lenlab[i].Text = " + " + c[i];
    this.Controls.Add(lenlab[i]);
}

Upvotes: 0

Views: 557

Answers (2)

Grant Winney
Grant Winney

Reputation: 66439

This line is causing every position in your array to have a reference to the same Label you created originally, outside the loop, which means all you're doing is changing the position and text of the same Label inside your loop.

lenlab[i] = lab;

The behavior you're seeing is due to the fact that you can only add a particular control to this.Controls once, so the effect is that you see the same label changing position.

Here's the portion of the Add() method that checks whether the control you're adding already has a parent, and if it does, then it removes it from it's current parent before adding it to the new one. So every time you call this.Controls.Add() with the same Label, it removes it from the Form and then adds it again.

// Remove the new control from its old parent (if any)
if (value.parent != null) {
    value.parent.Controls.Remove(value);
}

Instead, create a new Label inside your for loop:

lenlab[i] = new Label();

There are controls that can help you layout controls without the need to calculate a new position each time. In particular, read up on the FlowLayoutPanel and TableLayoutPanel classes.

Upvotes: 1

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

What you are doing there is basically create one Label, change it several times, and attach it several times to the page. What you end up having on the page is the last version of the Label being added once, which is the expected behavior.

If you want to add several labels, you need to new each of them.

Upvotes: 1

Related Questions