Populate control with set of labels
-
21-12-2019 - |
Question
I'm writing a program that get data from the registry and then adds groupboxes to a tabcontrol, and in the groupbox I'd like to create as many label controls (to display the registry info) as many data (key-value pairs) I got. To do this I made this function:
private void AddAllControl()
{
GroupBox TestGroupBox = new GroupBox();
TestGroupBox.AutoSize = true;
TestGroupBox.Text = "valami";
TestGroupBox.Height = 500;
for (int i = 0; i < 21; i++)
{
Label TempLabel = new Label();
TempLabel.Text = i.ToString();
TempLabel.Location = new System.Drawing.Point(20 + i, 30);
TempLabel.Show();
TempLabel.Visible = true;
TempLabel.Enabled = true;
TestGroupBox.Controls.Add(TempLabel);
}
tabPage_SandBox.Controls.Add(TestGroupBox);
}
This function is processed when a button been pressed. After that The groupbox appear correctly, but only 1 label the first (with text = 0) appear instead of 21 label.
When I stop to debug the program I see all the labels are exists and all the property are correct, however they do not appear.
There must be something that I didn't noticed.
And now my question? What did I wrong?
As you can see I tried both visible
and enabled
property but neither of bring me solution.
Solution
You have to set
TempLabel.AutoSize = true;
And you have to modify the location a little bit like
TempLabel.Location = new System.Drawing.Point(20 + 10 * i, 30);
or I think you want to have the labels one below the other so you have to set the location like
TempLabel.Location = new System.Drawing.Point(20, 20+20 * i);
OTHER TIPS
If your Labels are a constant size then
TestGroupBox.Controls.Add(new Label()
{
Text = i.ToString(),
Location = new Point(20 + (i*20), 30),
Size = new Size(20, 20)
});
Would do the trick