Create labels at runtime

倖福魔咒の 提交于 2020-01-01 18:57:12

问题


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:

 (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)


回答1:


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

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:

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


来源:https://stackoverflow.com/questions/14439733/create-labels-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!