Archive for February, 2008

Fixing FindControl in ASP.NET 2.0 and ASP.NET 3.5

After becoming used to having really powerful common functions built for your ASP.NET 1.1 apps, it’s very easy to forget they aren’t a part of the .NET Framework when you start a new project. One such common function I never realised I needed so much was a proper FindControl function.

Every ASP.NET developer defines a DataBound control with some kind of custom template at some point in their life. So how do you get at those controls in your fancy template at run time? Logically you would think FindControl would nail this requirement. Unfortunately it doesn’t really, so if you find yourself calling TextBox t = myListView.FindControl("TextBox1") as TextBox and getting nowhere, try this handy class:

using System.Web.UI;
public static class ControlHelper
{
    /// <summary>
    /// Performs a recursive FindControl returning a strongly typed object
    /// </summary>
    /// <typeparam name="T">Control Type to return</typeparam>
    /// <param name="parentControl">The Control to search from</param>
    /// <param name="id">The ID of the control you're looking for</param>
    /// <returns></returns>
    public static T FindControl<T>(Control parentControl, string id) 
where T : Control { Control found = parentControl.FindControl(id); if (found != null) { return (T)found; } foreach (Control ctrl in parentControl.Controls) { if (ctrl != null) { found = FindControl<T>(ctrl, id); if (found != null) { return (T)found; } } } return null; } public static T Find<T>(this Control parentControl, string id)
where T : Control { return FindControl<T>(parentControl, id); } }

Viola!

The cool thing about this function is I’ve made it support being used as an Extension method (Remove the bottom function if you aren’t running .NET 3.5), it’s recursive, and also it returns a strongly type object (because the System.Web.UI.Control type is useless on it’s own)

Now you can call myListView.Find<TextBox>("TextBox1");

Much neater!

Leave a comment