在运行时创建标签

时间:2013-01-21 13:28:55

标签: c# runtime labels

使用此代码,我可以在运行时创建标签:

ArrayList CustomLabel = new ArrayList();

foreach (string ValutaCustomScelta in Properties.Settings.Default.ValuteCustom)
{
     CustomLabel.Add(new Label());
     (CustomLabel[CustomLabel.Count - 1] as Label).Location = new System.Drawing.Point(317, 119 + CustomLabel.Count*26);
     (CustomLabel[CustomLabel.Count - 1] as Label).Parent = tabPage2;
     (CustomLabel[CustomLabel.Count - 1] as Label).Name = "label" + ValutaCustomScelta;
     (CustomLabel[CustomLabel.Count - 1] as Label).Text = ValutaCustomScelta;
     (CustomLabel[CustomLabel.Count - 1] as Label).Size = new System.Drawing.Size(77, 21);
     Controls.Add(CustomLabel[CustomLabel.Count - 1] as Control);
}

我需要在tabPage2上创建标签,但这行不起作用:

 (CustomLabel[CustomLabel.Count - 1] as Label).Parent = tabPage2;

在运行时在tabPage2上创建标签的正确指令是什么? (我使用visual studio 2010,windows form)

1 个答案:

答案 0 :(得分:4)

您需要将标签添加到标签页的Controls集合中:

tabPage2.Controls.Add(CustomLabel[CustomLabel.Count - 1] as Control);

顺便说一句:你不应该使用ArrayList。而是使用List<Label>。此外,首先初始化标签,然后将其添加到列表中。这使您的代码更具可读性:

List<Label> customLabels = new List<Label>();

foreach (string ValutaCustomScelta in Properties.Settings.Default.ValuteCustom)
{
    Label label = new Label();
    label.Location = new System.Drawing.Point(317, 119 + customLabels.Count*26);
    label.Parent = tabPage2;
    label.Name = "label" + ValutaCustomScelta;
    label.Text = ValutaCustomScelta;
    label.Size = new System.Drawing.Size(77, 21);
    customLabels.Add(label);
    tabPage2.Controls.Add(label);
}