Using LINQ, how do you get all label controls

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-05 05:35:07

问题


I want to get a collection of all label controls that are part of a user control. I have the following code:

        var labelControls = from Control ctl in this.Controls
                            where ctl.GetType() == typeof(Label)
                            select ctl;

but the result is zero results.

Please assist. Thanks.

Edit I have also tried the following code without success.

        this.Controls
            .OfType<Label>()
            .Where(ctl => ctl.ID.Contains("myPrefix"))
            .ToList()
            .ForEach(lbl => lbl.ForeColor = System.Drawing.Color.Black);

Again, without success.


回答1:


Are you sure that the control whose child controls you are parsing actually directly contains Label controls? I suspect that it is a child of the main control that is hosting the labels, in which case, you need to recursively search through the UI tree to find the labels.

Something like:

public static IEnumerable<Label> DescendantLabels(this Control control)
{
   return control.Controls.DescendantLabels();
}

public static IEnumerable<Label> DescendantLabels(this ControlCollection controls)
{
    var childControls = controls.OfType<Label>();

    foreach (Control control in controls)
    {
       childControls = childControls.Concat(control.DescendantLabels());
    }

    return childControls;
}



回答2:


Controls.OfType<Label>() - thats all

For nested controls

public static class ext
{
    public static List<Label> GetLabels(this Control control)
    {
        var chList = control.Controls.OfType<Label>().ToList();
        chList.AddRange(((IEnumerable<Control>)control.Controls)
              .SelectMany(c => c.GetLabels()));
        return chList;
    }
}



回答3:


var labelControls = this.Controls.OfType<Label>();


来源:https://stackoverflow.com/questions/2594314/using-linq-how-do-you-get-all-label-controls

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