palermo4 posted on June 29, 2009 18:32

I have rewritten this method a few times.  This time I have implemented it as an extension method of the Control class.

public static class ControlExtensions
{
    public static T FindControl<T>(this Control currentControl, string id) where T : Control
    {
        if (id.Equals(currentControl.ID, StringComparison.OrdinalIgnoreCase))
        {
            // return control calling this method
            return currentControl as T;
        }
        // initialize potential "found" control to null
        T potentialFoundControl = null;
 
        foreach (Control childControl in currentControl.Controls)
        {
            // recursive call to each child control 
            potentialFoundControl = ControlExtensions.FindControl<T>(childControl, id);
            // if result is not null, match has been found, break the loop
            if (potentialFoundControl != null) { break; }
        }
        return potentialFoundControl;
    }
}

Posted in: code  Tags:

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010 J. Michael Palermo IV