ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

FindControl<T>

Generic recursive FindControl.

Source

public static T FindControl<T>( this Control startingControl, string id) where T : Control
{
    T foundControl = default(T);

    int controlCount = startingControl.Controls.Count;

    foreach (Control c in startingControl.Controls)
    {
        if (c is T && string.Equals(id, c.ID, 
            StringComparison.InvariantCultureIgnoreCase))
        {
            foundControl = c as T;
            break;
        }
        else
        {
            foundControl = FindControl<T>(c, id);
            if (foundControl != null)
            {
                break;
            }
        }
    }
    return foundControl;
}

Example

Button UpdateButton = Page.FindControl<Button>("UpdateButton");

Author: John Adams

Submitted on: 22 jul 2011

Language: C#

Type: System.Web.UI.Control

Views: 7109