Object with all of form's controls to loop through ASP.NET

  • Thread starter Thread starter David A. Beck
  • Start date Start date
D

David A. Beck

Is there a way I can loop through a form object in ASP.NET codebehind like
in VB.NET and get all of the controls?
 
Use the Controls collection.

dim ctrl as Control
for each ctrl in Page.Controls
.....
next
 
You can loop through the controls collection.
However it gets complicated if you have controls nested within other
container controls.
Here's some code Kevin Spencer posted a while back that provides a good
demonstration using recursion.

Private Function FindChildControl(ByVal objSearchControl As
System.Web.UI.Control, _
ByVal strControlID As String) As Object

Dim objChildControl As System.Web.UI.Control
Dim objControl As System.Web.UI.Control

If objSearchControl.Controls.Count = 0 Return Nothing

For Each objChildControl in objSearchControl.Controls
objControl = FindChildControl(objChildControl, strControlID)
If Not IsNothing(objControl) Return objControl
Next

Return Nothing
End Function
 
Steve:

Thanks. This code searches for a given control name in a control that itself
has controls. I have not been sucessful yet in adapting it to loop through
the Page.Controls object for my "Form1" to get all the controls.

Dab
 
Back
Top