gpt4 book ai didi

c# - 在运行时创建标签

转载 作者:行者123 更新时间:2023-12-02 05:17:22 25 4
gpt4 key购买 nike

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

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

最佳答案

您需要将标签添加到 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);
}

关于c# - 在运行时创建标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14439733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com