Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Searching for sub-control by type

Sometimes you need to search for some sub controls and its ID doesn’t depends on you. For example, you don’t know how this control will be rendered in different conditions. Like SharePoint fields are rendered. You know that there must be one TextBox (… or other type) which you need to use to do some trick with it.

Following code can help you:

public static T FindControl<T>(Control control) where T : Control

{

    foreach (Control c in control.Controls)

    {

        if (c is T)

        {

            return (T)c;

        }

 

        if (c.HasControls())

        {

            T cTmp = FindControl<T>(c);

            if (cTmp != null)

            {

                return cTmp;

            }

        }

    }

 

    return null;

}

Using example:

TextBox c = FindControl<TextBox>(Page);

if (c == null)

{

    // Control not found

}

You can also modify this method to collect all controls of required type.

No Comments