Iterate though all controls on asp.net page

前端 未结 3 1797
误落风尘
误落风尘 2021-01-15 05:14

I\'m using ascx and I need to iterate through all of the controls and selects each that have cssClass attribute set to \'required\'.

I have the following code:

相关标签:
3条回答
  • 2021-01-15 05:49

    Regarding your comment on the answer above, you need to first check that it is a WebControl and then cast it to a WebControl

    var webControl = childControl as WebControl;
    
    if(webControl != null)
    {
       if(webControl.CssClass == 'required')
       // Do your stuff
    }
    
    0 讨论(0)
  • 2021-01-15 05:53

    The Control class doesn't have that CssClass property, the WebControl does. So try to cast your childControl to WebControl. If that worked, then you can access the CssClass property.

    WebControl webCtrl = childControl as WebControl;
    if (webCtrl != null)
    {
       webCtrl.CssClass = "test";
    }
    
    0 讨论(0)
  • 2021-01-15 06:02

    CssClass property is a member of the WebControl class.

    You have to check if the control is a webcontrol, or, if it's only a control, you can get the attribute "class" in the attributes collection.

    for example, you can do :

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

    You also have to iterate recursively. Code found here : 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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题