enumerating through page.controls

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi all,

I have an asp.net 2.0 web app that has an aspx page that has a Master page.
The Master page has the <form runat="server"> defined on it. Now the aspx
page has a UserControl that has a bunch of fields and fieldvalidators.
Inside the code behind of the ascx usercontrol I am trying to loop through
all controls to find all the validators and for some reason I am unable to
find any. Here is the code I am calling on the PreRender event handler of
the usercontrol.

private void InitFieldValidators()

{

int i;

Control c;

for (i = 0; i < this.Controls.Count; i++)

{

c = this.Controls;

SetReqdControl(c);

}

}

private void SetReqdControl(Control o)

{

if (o.HasControls())

{

int i;

Control c;

for (i = 0; i < o.Controls.Count; i++)

{

c = o.Controls;

SetReqdControl(c);

}

}

else

{

Response.Write(o.ID);

Response.Write("<br/>");

}

}
 
your recursion is wrong. you need to check the current control and
recurse check on all children. assuming the print is where the logic
goes, you are only handling child controls with no children.
 
I have an asp.net 2.0 web app that has an aspx page that has a Master page.
The Master page has the <form runat="server"> defined on it. Now the aspx
page has a UserControl that has a bunch of fields and fieldvalidators.
Inside the code behind of the ascx usercontrol I am trying to loop through
all controls to find all the validators and for some reason I am unable to
find any.

That's because they aren't in the Controls collection of the page. Only
a few of the controls of the page are, the other controls are in the
Controls collection of other controls.

You have to loop the Controls collections recursively to reach all the
controls of the page.
 
Back
Top