Archive

Posts Tagged ‘recursive’

Recursive generic extensionmethods are fun! (Recursive FindControl)

November 12th, 2008 No comments

Just thought I should share a little piece of code with you this evening. It’s a little extension method (i.e it requires .Net 3.5) that extends Control and helps you find all instances of a certain controltype under the Control on which you invoke the method. Just put the following code in an assembly (or a .cs-file in App_Code).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

/// <summary>
/// Holderclass for extension methods
/// </summary>
public static class ExtensionMethods
{
    /// <summary>
    /// Recursively searchs for all instances of a specified control type.
    /// </summary>
    /// <typeparam name="T">The type of control to search for.</typeparam>
    /// <param name="control">The control to search from.</param>
    /// <returns>A List<> with the found controls.</returns>
    public static List<T> FindControls<T>(this Control control) where T : Control
    {
        List<T> myList = new List<t>();
        FindControls</t><t>(control, ref myList);
        return myList;
    }

    private static void FindControls<T>(Control control, ref List<T> controlList) where T : Control
    {
        for (int i = 0; i < control.Controls.Count; i++)
        {
            Control currentControl = control.Controls[i];
            if (currentControl is T)
            {
                T typedControl = control.Controls[i] as T;
                controlList.Add(typedControl);
            }

            FindControls<T>(currentControl, ref controlList);
        }

    }
}

To call it you just invoke FindControls<Control>() on any object that derives from Control (i.e. Page, Label, Calendar, the list can go on forever), see the sample below. Hope you find some use for it!

List<HtmlMeta> meta = Page.FindControls<HtmlMeta>();