Thursday, December 16, 2010

C# and ASP.Net - Searching for a control recursively

At some point during my programming career I found I needed to search for a control on a page but had no way to know who the control's parent would be.  So after a little thinking I thought to myself "what if I could just search any parent and it's children recursively?".

This would give me the flexibility to search a specific parent control like a panel or an entire master page if needed.  So by adding the following methods to a "Search" class (or whatever you want to name it) you too can have this functionality:

    /// <summary>
    /// Searches through all child controls looking for the control name specified
    /// </summary>
    /// <param name="parentControl">
    /// Control - the control to search
    /// </param>
    /// <param name="controlName">
    /// string - control name to find
    /// </param>
    /// <param name="control">
    /// Control - control to bind to the found control
    /// </param>
    public static void FindControl(Control parentControl, string controlName, ref Control control)
    {
        if (control.ID == null)
        {
            SearchControl(parentControl, controlName, ref control);
        }


        if (parentControl.HasControls())
        {
            foreach (Control item in parentControl.Controls)
            {
                FindControl(item, controlName, ref control);
            }
        }
    }


    /// <summary>
    /// Helper method for FindControl
    /// </summary>
    private static void SearchControl(Control parentControl, string controlName, ref Control control)
    {
        if (parentControl.FindControl(controlName) != null)
        {
            control = parentControl.FindControl(controlName);
        }
    }


Pretty simple yeah?

So now you just have to call FindControl and pass in the parent control to search.  It will then search all of it's children parent controls looking for the control by name.  Once it finds the control its looking for it will assign a reference to the ref Control control parameter.  If it doesn't find it then the control you passed in will still be null or set to whatever it is you set it to before passing it in.

Happy control searching!

-Matt

No comments:

Post a Comment