August 7, 2006 6:32 pm...6:32 pm

Custom FindControl Implementation (C#)

Jump to Comments

Anyone who has ever used the native FindControl method built into the System.Web.UI.Page or System.Web.UI.Control classes knows that it pretty much stinks. From my experience using it, the only controls that it can find by name are those that are direct children of the container being searched. This isn’t helpful for most real world ASPX pages which may contain dozens of nested controls and/or third party tools.

So, here’s my own custom version of what FindControl should have been from the beginning.

First, override the FindControl method in your derived control and/or webform base class.


        public override Control FindControl(string id)
        {
            Control bc = null;
            try
            {
                bc = base.FindControl(id);
            }
            catch(HttpException)
            {
                bc = null;
            }
            return (bc != null) ? bc : MyUtility.FindControl(id, this.Controls);
        }

Now write the static utility methods to implement the recursive search if the native FindControl didn’t get what you wanted.


    public class MyUtility
    {
        public static Control FindControl(string id, ControlCollection col)
        {
            foreach (Control c in col)
            {
                Control child = FindControlRecursive(c, id);
                if (child != null)
                    return child;
            }
            return null;
        }

        private static Control FindControlRecursive(Control root, string id)
        {
            if (root.ID != null && root.ID == id)
                return root;

            foreach (Control c in root.Controls)
            {
                Control rc = FindControlRecursive(c, id);
                if (rc != null)
                    return rc;
            }
            return null;
        }
    }

Voila! Now you have the ability to find controls by name that are nested in the hairiest control structure you can come up with.

Check out Part II of this topic to see how to extend this implementation to find multiple controls by Type.

9 Comments


Leave a Reply