ASP.NET: Recursive FindControl & Extension Methods

Here's a really short and simple bit of code that has the potential to be a bit of a time-saver.

The FindControl method of the Control class is used to find a specific child control of a given parent, searching by ID. This method, however, doesn't search the control hierarchy recursively: it searches the direct children of the specified parent control only.

While writing a recursive version of this method is trivial, a rather nice way to make the method reusable is to implement it as an extension method. Here's how it can be done:

namespace Boo.Web.UI.Extensions

{

public static class ControlExtensions

{

    /// <summary>

    /// recursively finds a child control of the specified parent.

    /// </summary>

    /// <param name="control"></param>

    /// <param name="id"></param>

    /// <returns></returns>

    public static Control FindControlRecursive(this Control control, string id)

    {

        if (control == null) return null;

        //try to find the control at the current level

        Control ctrl = control.FindControl(id);

        if (ctrl == null)

        {

            //search the children

            foreach (Control child in control.Controls)

            {

                ctrl = FindControlRecursive(child, id);

                if (ctrl != null) break;

            }

        }

        return ctrl;

    }

}

}

And to call it:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using Boo.Web.UI.Extensions;

namespace MyWebApp

{

public partial class WebForm1 : System.Web.UI.Page

{

    public void Page\_Load(object sender, EventArgs e)

    {

        //call the recursive FindControl method

        Control ctrl = this.FindControlRecursive("my\_control\_id");

    }

}

}

Don't forget to import the namespace within which the extensions method class is declared- or a compilation error will not long follow.

Now, all you need to do is import this same namespace for any pages/user controls/custom controls which need to use the recursive control search and you're good to go.

Doing it this way is of course logically no different to creating a static method in a util class, and passing both the parent control and the ID of the child control you want to find to it, but considering how commonly this functionality is required, it's nice to be able to tack it onto the control class itself, and extension methods provide an elegant way to accomplish this.

This article is part of the GWB Archives. Original Author: Adam Pooler

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.