Reputation: 182
I use this code to add some labels to a windows form in c#:
Label[] lbl = new Label[temp+1];
for (int i = 0; i <= temp; i++) {
lbl[i] = new Label();
lbl[i].Text = "" + i;
lbl[i].Location = new Point(30 + (i * unit), 380);
lbl[i].Visible = true;
this.Controls.Add(lbl[i]);
}
There is not a serious problem but my code works for temps less than 5 and for temps greater than 5 it shows only the first one. What you think? where is the problem?
Upvotes: 1
Views: 246
Reputation: 28499
Make the labels automatically adjust their size to their content by setting their AutoSize
property to true
:
lbl[i] = new Label();
lbl[i].Text = "" + i;
lbl[i].Location = new Point(30 + (i * unit), 380);
lbl[i].Visible = true;
lbl[i].AutoSize = true;
this.Controls.Add(lbl[i]);
Without this, the labels have a fixed size. When this fixed size is greater than unit
, the labels overlap and hide each other's text. With more labels to add, unit
becomes smaller and then smaller than the default width of the labels when temp
is ≥ 5.
Alternatively, you could set the labels' width to unit
to make sure that they do not overlap.
Upvotes: 1