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

Extending Control class to search sub-control by type

I have already wrote in my previous post about searching sub controls by type.

Post: Searching for sub-control by type

Now I’m suggesting more useful extension-type method to extend all classes derived from Control class (for example Page, TextBox, DropDownList etc).

* Extension methods works in .NET 3.5 and newer.

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

    : Control

{

    foreach (Control c in control.Controls)

    {

        if (c is T)

        {

            return (T)c;

        }

 

        if (c.HasControls())

        {

            T cTmp = c.FindControl<T>();

            if (cTmp != null)

            {

                return cTmp;

            }

        }

    }

 

    return null;

}

Using examples:

TextBox firstLevelBox = Page.FindControl<TextBox>();

if (firstLevelBox != null)

{

    // just for example

    TextBox box = firstLevelBox.FindControl<TextBox>();

}

else

{

    // control not found

}

 

Don't miss to add using directive:

using System.Linq;

 

Don't miss also to add using namespace where you have defined this extension method, when you want to use it.

 

No Comments