在运行时创建标签(Create labels at runtime)

2019-08-07 16:33发布

有了这个代码,我可以在运行时创建标签:

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标签? (IM使用Visual Studio 2010,窗口形式)

Answer 1:

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

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

BTW:你不应该使用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);
}


文章来源: Create labels at runtime