looping through all webcontrols in htmlform

G

Guest

Hi. I'm trying to loop through all webcontrols in my
System.Web.UI.HtmlControls.HtmlForm.

This is my code:
Dim form As HtmlForm
Dim control As Control

form = Me.FindControl("completion")
For Each control In form.Controls
....
Next

Looking at the form.Controls.Count property it says that there are 109
controls on my page, but the For Each statement only does one loop where it
returns a LiteralControl. Am I missing something here? Shouldn't the loop
execute 108 times??

Thanks,
Shawn
 
K

Karl

You have to do this recursively. Your form only has 1 control, which has 4
controls, which each have 7 controls...and so on.

private sub recurse(byval c as Control)
for each child in c.Controls
if child .HasChildren then
recurse(child)
end if
end sub

Karl
 
B

Ben Lovell

Hi,

Remember, some of those controls contain controls themselves. Your code
sample doesn't recurse the control tree, it just iterates the top level
parent controls. You must write a recursive function similar to the
following (c#):

private void RecurseControls(ControlCollection controls)
{
foreach(Control c in controls)
{
//do something with control...

//recurse
if(c.HasControls())
RecurseControls(c.Controls);
}
}

Or in VB.NET:

Private Sub RecurseControls(ByVal controls As ControlCollection)
For Each control As Control In controls
'do something with control

'recurse
If control.HasControls() Then
RecurseControls(control.Controls)
End If
Next
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top