Geeks With Blogs

@darrenkopp
  • darrenkopp today's music playlist is completely nine inch nails, kmfdm, and mdfmk. about 16 hours ago
  • darrenkopp @joshkodroff then ran into problems with it actually changing when passing 4.0x86 / 4.0x64 from command line. so we just dropped to msbuild about 1 day ago
  • darrenkopp @joshkodroff was about a year ago but ran into issues with toggling x86 and x64 in build not working right and new version didn't support it about 1 day ago
  • darrenkopp started borderlands downloading, did the 7-minute workout. was done downloading by the end of it. sweet! about 1 day ago
  • darrenkopp invite link for new google maps... here we gooooooooooooooooooooo about 1 day ago
  • darrenkopp @craigber i wouldn't be surprised if gearbox had gone out of business with how many gaming studios have in fact burnt out lately about 1 day ago

Darren's Blog Where sense and sensibility don't meet

I came across a need the other day to recurse the page control tree (or any control tree really) to find all controls of a certain type, so this is the extension method I wrote to help me do that. Hopefully it will help others as well.

/// <summary>
/// Recurses the control tree and finds all controls in the control collection that are of the specified type.
/// </summary>
/// <typeparam name="T">The type of control you want to find</typeparam>
/// <param name="controls">The controls.</param>
/// <returns></returns>
public static IEnumerable<T> FindRecursive<T>(this ControlCollection controls)
{
    // create list of results
    List<T> results = new List<T>();

    // add controls in current control collection that match type
    results.AddRange(controls.OfType<T>());

    // recurse control tree
    foreach (Control c in controls)
    {
        // add controls to results
        results.AddRange(FindRecursive<T>(c.Controls));
    }

    return results;
}

 

This method could easily be extended to accept another parameter to specify the ID of the control. The method above does depend on System.Linq and .NET 3.5 (or at least visual studio 2008, because I believe that most of this is just a compiler trick).

Posted on Wednesday, February 20, 2008 9:16 AM Development , .NET | Back to top


Comments on this post: Recurse the Control Tree in ASP.NET

# re: Recurse the Control Tree in ASP.NET
Requesting Gravatar...
Very helpfull! Thanks.
Left by Richard77 on Aug 03, 2012 3:59 PM

Your comment:
 (will show your gravatar)
 


Copyright © Darren Kopp | Powered by: GeeksWithBlogs.net | Join free