Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through all the user controls on a page

Tags:

c#

asp.net

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

like image 740
Narmatha Balasundaram Avatar asked Apr 13 '10 18:04

Narmatha Balasundaram


2 Answers

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);
like image 98
CAbbott Avatar answered Oct 20 '22 02:10

CAbbott


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;
}
like image 36
Sani Singh Huttunen Avatar answered Oct 20 '22 01:10

Sani Singh Huttunen