Iterating custom controls

  • Thread starter Richard S. Byer
  • Start date
R

Richard S. Byer

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.
 
J

John Saunders

Richard S. Byer said:
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?

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...
 
R

Richard S. Byer

Thanks John, but as I said - the controls do not show in Page.Controls, and
recursion does not work with 'this'.
 
J

John Saunders

Richard S. Byer said:
Thanks John, but as I said - the controls do not show in Page.Controls, and
recursion does not work with 'this'.

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.
 

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

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top