asp.net - 遍历asp.net页面上的所有控件

标签 asp.net css iteration

我正在使用 ascx,我需要遍历所有控件并选择每个 cssClass 属性设置为“required”的控件。

我有以下代码:

foreach (Control masterControl in Page.Controls)
        {
            if (masterControl is MasterPage)
            {
                foreach (Control formControl in masterControl.Controls)
                {
                    if (formControl is System.Web.UI.HtmlControls.HtmlForm)
                    {
                        foreach (Control contentControl in formControl.Controls)
                        {
                            if (contentControl is ContentPlaceHolder)
                            {
                                foreach (Control childControl in contentControl.Controls)
                                {

                                }
                            }
                        }
                    }
                }
            }
        }

但是..我无法访问childControl.CssClass。我如何访问它?

提前致谢!

最佳答案

CssClass属性是 WebControl class 的成员.

你必须检查该控件是否是一个Web控件,或者,如果它只是一个控件,你可以在属性集合中获取属性“class”。

例如,您可以这样做:

List<WebControl> wcs = new List<WebControl>();
GetControlList<WebControl>(Page.Controls, wcs)
foreach (WebControl childControl in wcs)
{
     if(childControl.CssClass == "required") {
          // process the control
     }
}

您还必须递归迭代。代码在这里找到:Using C# to recursively get a collection of controls from a controlcollection :

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

关于asp.net - 遍历asp.net页面上的所有控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6422865/

相关文章:

python - 日期比较/连续日期分组

list - 如何在 haskell 中进行有状态列表操作

c# - 从远程 HTML 页面调用 *.aspx 函数

asp.net - 从一个浏览器复制的网址在另一浏览器中不起作用

html - 为什么这个容器 div 比包装它包含的图像所需的高?

javascript - 子元素位置相对工作错误

c# - 请推荐一个将asp.net网站迁移到三层架构的方案

c# - 执行阅读器 : Connection property has not been initialized

html - 为什么 "&lt;! --"注释掉一条样式规则,而 "&lt;!--"却没有?

c# - 数组的前向和后向搜索算法