How to find user controls?

  • Thread starter Thread starter TomislaW
  • Start date Start date
This is one way:

' Visual Basic .NET
Dim form As HtmlForm = Me.FindControl (<form id>)
For Each ctl2 As Control In form.Controls
If (TypeOf ctl2 Is UserControl) Then
Response.Write(ctl2.ID)
End If
Next

How to find all user controls (ascx) loaded on a Page?
 
You'd probably need to recurse that algorithm down each control's Controls
collection (reguardless of whether or not it's a UserControl)

Karl
 
Hello Shiva,

Or, even easier...

C#:
foreach (UserControl uc in this.Page.Controls)
{
// do something
}

VB.NET
For Each uc As UserControl in Me.Page.Controls
' do something
Next
 
some of user controls are inside other user controls or panels etc.
so I did this with recursion.
 
Hi Matt,
Or, even easier...

C#:
foreach (UserControl uc in this.Page.Controls)
{
// do something
}

Did you try this out? It won't work. Why? Because the User Controls are in
the WebForm, which is in the Page. You have to loop through the Form's
Controls Collection, not the Page's.

And what if the Control is nested inside another Control? The Controls
Collection of a Control doesn't contain the nested Controls. They are in the
Controls Collections of the Controls they immediately reside in.

The only way to truly find a Control whose location is not exactly known is
to use a recursive function that checks all Controls inside a given
Control's Controls Collection, and then calls itself for each Control in
that Collection. And start from the Form, not the Page, unless you expect a
given Control to be outside the form.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
I get paid good money to
solve puzzles for a living
 
Hello Kevin,

Of course, you're right regarding the WebForm portion.

The whole point of my response was to show that you dont have to do a loop
on Control and type check it for UserControl. You can do the foreach directly
on the UserControl type.
 
Back
Top