Want to loop through all the user controls that exist on the page and get their IDs. How do I do it?
Asked
Active
Viewed 1.8k times
5
-
Is this WinForms, WPF or ASP.NET? I suspect the latter, but you never know. – ChrisF Apr 13 '10 at 18:50
-
By "user controls" do you mean *managed controls* or specifically user controls (.ascx)? – CAbbott Apr 13 '10 at 18:51
-
@ChrisF: You guess it right! ASP.Net it is @CAbbott: .ascx – Narmatha Balasundaram Apr 13 '10 at 18:51
4 Answers
12
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);

CAbbott
- 8,078
- 4
- 31
- 38
-
if (curControl is UserControl) is never true. And I do have a usercontrol on the page – Narmatha Balasundaram Apr 13 '10 at 19:06
-
1I've tested this on a page where I have a user control and it finds it. Are you deriving your control from `System.Web.UI.UserControl`? – CAbbott Apr 13 '10 at 19:09
3
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;
}

Sani Huttunen
- 23,620
- 6
- 72
- 79
2
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

cjbarth
- 4,189
- 6
- 43
- 62
2
foreach(Control control: Page.Controls)
{
//do something with control object
}

Midhat
- 17,454
- 22
- 87
- 114
-
But then, it loops through all controls. How can a user control be differentiated. GetType()?? – Narmatha Balasundaram Apr 13 '10 at 18:53
-
1Controls can be nested so you need a recursive function to loop through all controls. – Dan Diplo Apr 13 '10 at 18:55