Friday, September 4, 2015

How to find a control in ASP.NET page recursively

Here is a sample code to find a asp.net control. You have to pass the parent control within which you need to search and the id of control to be searched as params.
public static Control FindControlRecursive(Control parent, string id)
{
    // If the control we're looking for is parent, return it
    if (parent.ID == id) return parent;

    // Else search through children
    foreach (Control control in parent.Controls)
    {
        Control found = FindControlRecursive(control, id);
        if (found != null) return found;
    }

    // No control with id is found
    return null;
}

No comments:

Post a Comment