获取特定类型的所有Web控件在页面上 [英] Get All Web Controls of a Specific Type on a Page

查看:126
本文介绍了获取特定类型的所有Web控件在页面上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在琢磨怎样才能得到一个网页上的所有控件,然后在此相关的问题对他们执行任务:

I have been pondering how I can get all controls on a page and then perform a task on them in this related question:

<一个href=\"http://stackoverflow.com/questions/869122/how-to-search-through-a-c-dropdownlist-programmatically\">How搜索通过一个C#编程的DropDownList

我需要code,可以扫描的页面,让所有DropDownList控件,并在列表中返回他们。

I need code that can scan the page, get all DropDownList Controls and return them in a list.

我目前不必编辑每一个人控制,我宁愿能够动态地遍历每个控件preform我的任务。

I'm currently having to edit each individual control, I would rather be able to dynamically loop over each control to preform my task.

推荐答案

检查<一href=\"http://stackoverflow.com/questions/6422865/iterate-though-all-controls-on-asp-net-page/6422908#6422908\">my previous SO回答。

基本上,这个想法是用包裹通过控件集合迭代的递归:

Basically, the idea is to wrap the recursion of iterating through the controls collection using :

private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
where T : Control
{
    foreach (Control control in controlCollection)
    {
        //if (control.GetType() == typeof(T))
        if (control is T) // This is cleaner
            resultCollection.Add((T)control);

        if (control.HasControls())
            GetControlList(control.Controls, resultCollection);
    }
}

和使用它:

List<DropDownList> allControls = new List<DropDownList>();
GetControlList<DropDownList>(Page.Controls, allControls )
foreach (var childControl in allControls )
{
//     call for all controls of the page
}

:这里是达到这一目标的更优雅的方式。我写了两个扩展方法,可以走控件树在两个方向。这些方法都写在一个更LINQ的方式,因为它产生一个可枚举:

: here is a more elegant way to reach this goal. I wrote two extensions methods that can walk the control tree in both directions. The methods are written in a more Linq way as it produces an enumerable:

/// <summary>
/// Provide utilities methods related to <see cref="Control"/> objects
/// </summary>
public static class ControlUtilities
{
    /// <summary>
    /// Find the first ancestor of the selected control in the control tree
    /// </summary>
    /// <typeparam name="TControl">Type of the ancestor to look for</typeparam>
    /// <param name="control">The control to look for its ancestors</param>
    /// <returns>The first ancestor of the specified type, or null if no ancestor is found.</returns>
    public static TControl FindAncestor<TControl>(this Control control) where TControl : Control
    {
        if (control == null) throw new ArgumentNullException("control");

        Control parent = control;
        do
        {
            parent = parent.Parent;
            var candidate = parent as TControl;
            if (candidate != null)
            {
                return candidate;
            }
        } while (parent != null);
        return null;
    }

    /// <summary>
    /// Finds all descendants of a certain type of the specified control.
    /// </summary>
    /// <typeparam name="TControl">The type of descendant controls to look for.</typeparam>
    /// <param name="parent">The parent control where to look into.</param>
    /// <returns>All corresponding descendants</returns>
    public static IEnumerable<TControl> FindDescendants<TControl>(this Control parent) where TControl : Control
    {
        if (parent == null) throw new ArgumentNullException("control");

        if (parent.HasControls())
        {
            foreach (Control childControl in parent.Controls)
            {
                var candidate = childControl as TControl;
                if (candidate != null) yield return candidate;

                foreach (var nextLevel in FindDescendants<TControl>(childControl))
                {
                    yield return nextLevel;
                }
            }
        }
    }
}

感谢这个关键字,这些方法扩展方法和可以简化code。

Thanks to the this keyword, these methods are extensions methods and can simplify the code.

例如,要查找所有的DropDownList 页面,你可以简单地调用:

For example, to find all DropDownList in the page, you can simply call:

var allDropDowns = this.Page.FindControl<DropDownList>();

由于使用了收益关键字的,因为LINQ的是足够聪明推迟枚举的执行,可以调用(例如):

Because of the use of the yield keyword, and because Linq is smart enough to defer execution of the enumeration, you can call (for example):

var allDropDowns = this.Page.FindControl<DropDownList>();
var firstDropDownWithCustomClass = allDropDowns.First(
    ddl=>ddl.CssClass == "customclass"
    );

枚举将立即停止为在首先,predicate 方法是满意的。整个控制树不会被踩到。

The enumeration will stop as soon as the predicate in the First method is satisfied. The whole control tree won't be walked.

这篇关于获取特定类型的所有Web控件在页面上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆