简体   繁体   English

如何从控件集合中检索具有特定属性的控件?

[英]How to retrieve a control with a certain property from a collection of Controls?

I create a menu application in an ASP.NET app like this: 我在ASP.NET应用程序中创建菜单应用程序,如下所示:

// HTML
<td runat="server" id="container">

// C#. This logic is creating
// within a LOOP
Label l = new Label("name_blabla");
Panel p = new Panel();
p.Add(l);
container.Controls.Add(p);

At a given moment I assing the CSS class myclass to the label l : 在给定的时刻,我将CSS类myclass赋给标签l

l.CssClass="myClass";

So the container has only one panel containing only one label with this myclass name assigned. 因此,该容器只有一个面板,其中仅包含一个分配了此myclass名称的标签。

The purpose is to get this panel from the container once all controls are inserted. 目的是在插入所有控件后从容器中获取此面板。 I don't know the position where it is inserted. 我不知道它插入的位置。 Better with LINQ. 使用LINQ更好。

You can use OfType<>() to filter panels, then apply SelectMany() to project the labels inside your panels, then Where() to check the CSS classes of the labels: 您可以使用OfType<>()过滤面板,然后应用SelectMany()将标签投影到面板内,然后使用Where()检查标签的CSS类:

Label theLabel
    = container.Controls.OfType<Panel>()
                        .SelectMany(panel => panel.Controls.OfType<Label>())
                        .Where(label => label.CssClass == "MyClass")
                        .FirstOrDefault();

EDIT: If you want to match the panel instead of the label, you can use Any() : 编辑:如果要匹配面板而不是标签,则可以使用Any()

Panel thePanel
    = container.Controls.OfType<Panel>()
                        .Where(panel => panel.Controls.OfType<Label>().Any(
                            label => label.CssClass == "MyClass"))
                        .FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM