2

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

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 窗体)

4

1 回答 1

5

您需要将标签添加到标签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);
}
于 2013-01-21T13:30:40.770 回答