Jevgeni Borozna's blog

SharePoint, ASP .NET

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.

Comments

Extending Control class to search sub-control by type | I love .NET! said:

Pingback from  Extending Control class to search sub-control by type | I love .NET!

# January 6, 2010 1:19 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)