迭代尽管asp.net页面上的所有控件

时间:2011-06-21 09:08:04

标签: 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。我该如何访问它?

提前致谢!

3 个答案:

答案 0 :(得分:4)

CssClass属性是WebControl class的成员。

您必须检查控件是否为webcontrol,或者,如果它只是一个控件,您可以在属性集合中获取属性“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);
    }
}

答案 1 :(得分:1)

Control类没有那个CssClass属性,WebControl属性。因此,请尝试将childControl转换为WebControl。如果可行,则可以访问CssClass属性。

WebControl webCtrl = childControl as WebControl;
if (webCtrl != null)
{
   webCtrl.CssClass = "test";
}

答案 2 :(得分:0)

关于您对上述答案的评论,您需要先检查它是WebControl,然后将其投放到WebControl

var webControl = childControl as WebControl;

if(webControl != null)
{
   if(webControl.CssClass == 'required')
   // Do your stuff
}