FindControl() recursively using an Extension Method

by brad 26. January 2010 11:15

FindControl() is great if you’re looking for a control one level down, but if you’re making a dynamic control with n levels of child controls it can become a pain… Extension Methods to the rescue!

Not only does it find the control your looking for at any level in the page, it also used generics to return the control without needing to cast it.

/// <summary>
/// Finds the control (Recursively) with an ID matching that given, of the Type requested.
/// No need to cast either!
/// </summary>
/// <typeparam name="T">The type of control to return</typeparam>
/// <param name="ctrl">The CTRL.</param>
/// <param name="ID">The ID of the control to find (recursively).</param>
/// <returns>The first child control with the matching ID of the requested Type.</returns>
public static T FindControl<T>(this Control ctrl, string ID) where T : Control
{
//Is the current control the one we're looking for?
if (ctrl.ID != null && ctrl.ID == ID && ctrl is T)
return (T)ctrl;

//Loop through every child control
foreach (Control child in ctrl.Controls)
{
//Does this child have the matching ID?
if (child.ID != null && child.ID.Equals(ID) && child is T)
return (T)child;

//Check the child's children (if it has any!)
if (child.Controls.Count > 0)
{
Control found = FindControl<T>(child, ID);
//Was the control found? if so return it!
if (found != null && found is T)
return (T)found;
}
}
//If we've got this far nothing has be found at this level (or below)
return null;
}

Tags:

ASP.NET | .NET 3.5 | C#

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  July 2010  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar