all groups > asp.net building controls > june 2004 >
You're in the

asp.net building controls

group:

Iterating custom controls


Iterating custom controls Richard S. Byer
6/6/2004 6:47:30 PM
asp.net building controls:
Here's a simple problem that's eating my lunch:

I need to write a base class method in ASP.NET that will iterate the page
and find all controls of a certain type. The type is a custom web control
that I created. The controls are never found in Page.Controls - instead,
using the debugger, I see them right off of 'this'. As in
'this.myControl1'. 'this' doesn't support iteration, so how can I find
custom controls of a certain interest to me?

Thanks if you can offer any ides,

Rich.

Re: Iterating custom controls John Saunders
6/7/2004 8:19:05 AM
[quoted text, click to view]

You will need to recurse. Go through each control in Page.Controls. If it is
the correct type, then stop. Otherwise, go through each control in that
control...
--
John Saunders
johnwsaundersiii at hotmail

Re: Iterating custom controls Richard S. Byer
6/7/2004 9:18:21 AM
Thanks John, but as I said - the controls do not show in Page.Controls, and
recursion does not work with 'this'.


[quoted text, click to view]

Re: Iterating custom controls John Saunders
6/7/2004 1:56:59 PM
[quoted text, click to view]

Are you saying that there are no controls at all in Page.Controls? Try this:

private void Page_Load(object sender, EventArgs e)
{
Control foundControl = RecursiveFind(Page.Controls);
}

private Control RecursiveFind(ControlCollection controls)
{
foreach (Control control in controls)
{
if (control is MyCustomType)
{
return control;
}
else
{
Control found = RecursiveFind(control.Controls);
if (found != null)
{
return found;
}
}

return null;
}
}

If you need a VB.Net version, please let me know.
--
John Saunders
johnwsaundersiii at hotmail

AddThis Social Bookmark Button