在运行时创建标签 [英] Create labels at runtime

查看:136
本文介绍了在运行时创建标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}



我需要创建tabPage2标签,但该行不行:

I need create labels on tabPage2, but this row not work:

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



这是正确指令,在运行时创建tabPage2标签? (IM使用Visual Studio 2010,Windows窗体)

Which is the correct instruction to create label on tabPage2 at runtime? (Im using visual studio 2010, windows form)

推荐答案

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

You need to add the labels to the Controls collection of the tab page:

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



BTW:你不应该使用的ArrayList 。相反,使用列表与LT;标签> 。此外,第一初始化标签,比它添加到列表中。这使你的代码了很多更具可读性:

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:

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);
}

这篇关于在运行时创建标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆