我一直在思考如何在一个页面上获取所有控件,然后在相关问题中对它们执行任务:

How to Search Through a C# DropDownList Programmatically

我需要的代码,可以扫描页面,获得所有DropDownList控件,并返回到一个列表中.

我目前必须编辑每个单独的控件,我宁愿能够动态循环每个控件来完成我的任务.

推荐答案

my previous SO answer美元.

基本上,我们的 idea 是使用以下命令包装遍历Controls集合的递归:

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
}

[Edited 11/26/2013]:这里有一个更优雅的方式来实现这个目标.我编写了两个扩展方法,可以在两个方向上遍历控制树.这些方法以更Linq的方式编写,因为它会生成一个可枚举的:

/// <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;
                }
            }
        }
    }
}

由于this关键字,这些方法是扩展方法,可以简化代码.

例如,要查找页面中的全部DropDownList个,只需调用:

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

由于使用了yield关键字,而且Linq足够聪明,可以推迟枚举的执行,因此可以调用(例如):

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

一旦First方法中的谓词得到满足,枚举就会停止.整个控制树都无法行走.

Asp.net相关问答推荐

如何处理当前文件中基本文件中的S onClick方法

授权错误错误 400:C# 上的 redirect_uri_mismatch

无法加载文件或程序集.无效指针(HRESULT 异常:0x80004003 (E_POINTER))

在 lambda 表达式中否定 Func

如何删除字符串的定义部分?

ASP.NET Response.Redirect 使用 302 而不是 301

HttpContext.Current.Request.IsAuthenticated 和 HttpContext.Current.User.Identity.IsAuthenticated 有什么区别?

如何通过后面的代码不显示

带有 ASP.NET MVC 6 锚标记助手的 QueryString

上传时验证大文件

如何在 ASP.NET 下拉列表中添加选项组?

如何从 JS 访问 ViewBag

HttpContext.Current 在 MVC 4 项目中未解决

回发不适用于 aspx 页面作为默认文档

在 Visual Studio 2010 中随机禁用编辑 aspx/ascx 文件?

Azure 网站 301 重定向 - 我应该把它放在哪里?

在 Asp.Net Core 中动态更改连接字符串

ASP.NET MVC 和 httpRuntime executionTimeout

ASP.NET MVC 5 Web.config:FormsAuthenticationModule或FormsAuthentication

ASP.NET 5 (vNext) - 获取配置设置