C# 在运行时创建标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14439733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create labels at runtime
提问by Vincenzo Lo Palo
With this code I can create labels at runtime:
使用此代码,我可以在运行时创建标签:
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);
}
I need create labels on tabPage2, but this row not work:
我需要在 tabPage2 上创建标签,但这一行不起作用:
(CustomLabel[CustomLabel.Count - 1] as Label).Parent = tabPage2;
Which is the correct instruction to create label on tabPage2 at runtime? (Im using visual studio 2010, windows form)
哪个是在运行时在 tabPage2 上创建标签的正确指令?(我使用的是 Visual Studio 2010,windows 形式)
采纳答案by Daniel Hilgarth
You need to add the labels to the Controls
collection of the tab page:
您需要将标签添加到标签Controls
页的集合中:
tabPage2.Controls.Add(CustomLabel[CustomLabel.Count - 1] as Control);
BTW: You shouldn't be using ArrayList
. Instead use a List<Label>
. Furthermore, first initialize the label, than add it to the list. This makes your code a lot more readable:
顺便说一句:你不应该使用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);
}