Loop through all the user controls on a page

后端 未结 4 1069
小蘑菇
小蘑菇 2020-12-19 12:34

Want to loop through all the user controls that exist on the page and get their IDs. How do I do it?

相关标签:
4条回答
  • 2020-12-19 12:56
    foreach(Control control: Page.Controls)
    {
    
        //do something with control object
    
    }
    
    0 讨论(0)
  • 2020-12-19 13:04

    I created an extension method to do this, which works really nicely with LINQ.

    <Extension()>
    Public Function DecendentControls(ParentControl As Control) As Control()
        Dim controls As New List(Of Control)
    
        For Each myControl As Control In ParentControl.Controls
            controls.Add(myControl)
            controls.AddRange(myControl.DecendentControls)
        Next
    
        Return controls.ToArray
    End Function
    

    Then with LINQ you can do something like this to set all the checkboxes on a page to unchecked:

    For Each myControl As CheckBox In pnlMain.DecendentControls.Where(Function(x) TypeOf x Is CheckBox)
        myControl.Checked = False
    Next
    
    0 讨论(0)
  • 2020-12-19 13:09

    To get each User Control, you'd have to test the Type of the control:

    EDIT: I modified my example to go through all controls recursively:

    Method

    public void GetUserControls(ControlCollection controls)
    {
        foreach (Control ctl in controls)
        {
            if (ctl is UserControl)
            {
                // Do whatever.
            }
    
            if (ctl.Controls.Count > 0)
                GetUserControls(ctl.Controls);
        }
    }
    

    Called

    GetUserControls(Page.Controls);
    
    0 讨论(0)
  • 2020-12-19 13:19

    This should work:

    var listOfUserControls = GetUserControls(Page);
    
    ...
    
    public List<UserControl> GetUserControls(Control ctrl)
    {
      var uCtrls = new List<UserControl>();
      foreach (Control child in ctrl.Controls) {
        if (child is UserControl) uCtrls.Add((UserControl)child);
        uCtrls.AddRange(GetUserControls(child);
      }
    
      return uCtrls;
    }
    
    0 讨论(0)
提交回复
热议问题