Thursday, March 22, 2012

looping through all webcontrols in htmlform

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,
ShawnYou 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
"Shawn" <Shawn@.discussions.microsoft.com> wrote in message
news:CBEED8BE-862D-4804-9FD5-4F79AC3B3AAB@.microsoft.com...
> 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
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

--
Ben
http://bitarray.co.uk/ben

"Shawn" <Shawn@.discussions.microsoft.com> wrote in message
news:CBEED8BE-862D-4804-9FD5-4F79AC3B3AAB@.microsoft.com...
> 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

0 comments:

Post a Comment