zl程序教程

您现在的位置是:首页 >  其他

当前栏目

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

ampNetASP 如何 获取 类型 控件 所有
2023-09-27 14:26:14 时间

一、

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
    }