Wednesday, 21 April 2010

ASP.NET: Using FindControl Recursively.

FindControl can be a bit of a pain, especially as it doesn't contain recursive support; that being, you need to know the direct parent of an object before you can start your search.

I have attached a method which is useful, especially when creating generic methods for groups of objects where the parent is unknown.

        /// <summary>
        /// Finds a Control recursively. Note finds the first match and exists
        /// </summary>
        /// <param name="RootControl">Root control to start looking in.</param>
        /// <param name="ControlToFind">The control to find within it recursively.</param>
        /// <returns>The control if it exists.</returns>
        public Control FindControlRecursive(Control RootControl, string ControlToFind)
        {
            if (RootControl.ID == ControlToFind)
                return RootControl;
 
            foreach (Control Ctl in RootControl.Controls)
            {
                Control FoundCtl = FindControlRecursive(Ctl, ControlToFind);
                if (FoundCtl != null)
                    return FoundCtl;
            }
 
            return null;
        }

No comments: