Find All Controls On A Page With Recursion

by Kaschimer 18. June 2009 04:39

I read a blog post here that discussed how to find all controls on a page, and the author did it using nested For loops, though he does point out that it can be done using a recursive function.

I recently had to solve this problem on a site I was working on, and I created the recursive algorithm for doing the same thing. Like I say, more than one way to skin a website...

Here it is in two parts. The first is the actual algorithm. To set the context, I loop through each control on my page and dynamically initialize properties about the control if it is a specific type:

 

''' <summary>

''' Initializes the help recursive.

''' </summary>

''' <param name="colControl">The col control.</param>

Private Sub InitializeHelpRecursive(ByRef colControl As ControlCollection)

    For Each c As Control In colControl

        If TypeOf (c) Is AppHelpIcon Then

            Me.InitalizeHelp(c)

        ElseIf c.HasControls Then

            InitializeHelpRecursive(c.Controls)

        End If

    Next

End Sub

 

The next part is just the method that starts the ball rolling. In this case, the PreRender Event of the page:

   

''' <summary>

''' Handles the PreRender event of the Page control.

''' </summary>

''' <param name="sender">The source of the event.</param>

''' <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>

Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender

    InitializeHelpRecursive(Me.Controls)

End Sub

 

This works like a charm, and since everything is a "Control" we end up hitting every control on the page. Both approaches are valid, and as the author points out, his method won't hit EVERY control.

Tags: , ,

Programming

Calendar

<<  September 2014  >>
MoTuWeThFrSaSu
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

View posts in large calendar
Get Microsoft Silverlight
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2014 Dash Technical Notes