Enable at runtime a series of serially named Label controls using c#

浪子不回头ぞ 提交于 2019-12-25 07:12:05

问题


I have some label control named as follows : Label1, Label2, Label3.......Label14, disabled at design time. Now i want to enable them using a for loop in the following manner

for(int i=1;i<15;i++)
{
    (Label+i).Enabled = true;
}

Obviously the above code does not compile.

Label1.Enabled = true;
Label2.Enabled = true;
Label3.Enabled = true;
...........
Label14.Enabled = true;

Is there any other way of achieving the desired result other than the way mentioned just above.Hope i make myself clear.Please advice with code.Thanks in advance


回答1:


you can get controls by name from parent's Controls collection

for(int i = 1; i < 15; i++)
{
    Control label = this.Controls["Label"+i];
    if (label != null) 
        label.Enabled = true;
}

In this example this refers to the form. If labels belong to another parent control (e.g. Panel or GroupBox) it should be used instead of this




回答2:


You can put your labels into a list and iterate through that list:

List<Label> myLabels = new List<Label> { Label1, Label2, /*...*/ Label14};
foreach(Label lbl in myLabels) lbl.Enabled = true;

If these are the only lables in your Form you can also do something like that:

foreach(Label lbl in this.Controls.OfType<Label>())
    lbl.Enabled = true;

This iterates through all (top level) control in your Form and takes all of type Label to set Enabled to true.




回答3:


You could stick them into an Enumerable and then use a foreach to iterate through them.

List<Label> lblList = new List<Label> { Label1, Label2, Label3, Label4 };

foreach (Label label in lblList)
{
    label.Enabled = true;
}

For a cleaner looking solution you could use the following syntax.

lblList.ForEach(x => x.Enabled = true);


来源:https://stackoverflow.com/questions/37681997/enable-at-runtime-a-series-of-serially-named-label-controls-using-c-sharp

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