Asp.Net 如何获取所有控件&如何获取指定类型的所有控件

一、

Asp.Net Page页面中访问所有控件的属性为:

Page.Controls

控件的结构是树结构。

二、获取指定类型所有控件实例:

1.递归方法定义:

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

2.使用调用:

    List<Literal> allControls = new List<Literal>();
    GetControlList<Literal>(Page.Controls, allControls);
    foreach (var childControl in allControls)
    {
        //call for all controls of the page
    }
原文地址:https://www.cnblogs.com/tianma3798/p/6128359.html