简体   繁体   English

查找与谓词匹配的所有ASP.NET控件?

[英]Find all ASP.NET controls matching a predicate?

I need to enumerate over a collection of controls - regardless of their nesting level - that match a given predicate. 我需要枚举与给定谓词匹配的控件集合(无论其嵌套级别如何)。

Originally the problem occurred, when I needed to set all textbox's in a grids row to ReadOnly , if a column in that row indicated that the record should not be editable. 最初,当我需要将网格行中的所有文本框设置为ReadOnly ,出现问题,如果该行中的某一列指示该记录不可编辑。

Later I realized, that I already solved a problem in the past very much like this one, only with a different criteria (find a single control recursively by its ID). 后来我意识到,过去我已经解决了一个非常类似的问题,只是使用不同的条件(通过ID递归地找到一个控件)。

After trying a few alternatives I came up with a general solution that works. 在尝试了几种选择之后,我想出了一个通用的解决方案。 But since I will use this method very often, I wanted to gather possible improvements. 但是由于我将经常使用此方法,因此我想收集可能的改进。

This method will return all child controls matching a predicate: 此方法将返回所有与谓词匹配的子控件:

 public static IEnumerable<T> FindChildControls<T>(this Control parentControl, Predicate<Control> predicate) where T : Control { foreach (Control item in parentControl.Controls) { if (predicate(item)) yield return (T)item; foreach (T child in item.FindChildControls<T>(predicate)) { yield return child; } } } 

Using this method I can do the following: 使用此方法,我可以执行以下操作:

var allTxt = Page.FindChildControls<TextBox>(c => c is TextBox);
var submit = Page.FindChildControls<Button>(c => c.ID == "btnSubmit").First();

You can use a queue to get rid of recursion if you want. 如果需要,您可以使用队列摆脱递归。

        public static IEnumerable<T> FindChildControls<T>(Control parentControl,
        Predicate<Control> predicate) where T : Control
        {
            Queue<Control> q = new Queue<Control>();

            foreach (Control item in parentControl.Controls)
            {
                q.Enqueue(item);
            }

            while (q.Count > 0)
            {
                Control item = q.Dequeue();
                if (predicate(item))
                    yield return (T)item;

                foreach (Control child in item.Controls)
                {
                    q.Enqueue(child);
                }
            }

        }

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

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