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.