Tuesday, June 1, 2010

ASP.NET FindControl recursively - a simple iterative approach

Hi guys!

The problem:
A common problem most people face when working with ASP.NET pages is the FindControl(string id) method. It works great, but it does only what it's supposed to - it searches for the control in some naming container. What if you have multiple naming containers nested? In this case, the FindControl method is not working anymore.

The idea of the solution:
The idea is very simple, because you have only one choice - search through the whole container hierarchy until you find the control you are searching for or you have traversed all the controls.

Recursive solution:
There are many places, where the recursive solution is explained, for instance: ASP.NET 2.0 MasterPages and FindControl() is probably the most famous one.

Simple iterative approach:
Playing with algorithms is always fun. The recursive solution is nothing more than an implementation of a standard traversal algorithm - Depth First Search Algorithm. It's simple, easy and working. But what if we want to use an iterative solution? Then the answer is just to implement the Breadth First Search Algorithm. A sample implementation follows below:


private Control FindControlById(Control containerControl,
    string controlId)
{
  Queue<Control> queue = new Queue<Control>();
  queue.Enqueue(containerControl);

  while(queue.Count > 0)
  {
    Control currentControl = queue.Dequeue();

    if(currentControl.ID == controlId)
    {
      return currentControl;
    }

    foreach(Control childControl in currentControl.Controls)
    {
      queue.Enqueue(childControl);
    }
  }

  return null;
}


Happy coding!