this.FindControl C# 2.0 and up

Lets start with a quote from msdn about extensions in C#.

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Here is the code to find the control you want to use.

public static class Extensions
{
    public static System.Windows.Forms.Control FindControl(this System.Windows.Forms.Control ctrl, string name)
    {
        if (ctrl != null)
        {
            // Is this the item we are loking for?
            if (ctrl.Name == name)
            {
                 // Yes it is!
                 return ctrl;
            }

            foreach (System.Windows.Forms.Control c in ctrl.Controls)
            {
                System.Windows.Forms.Control found = c.FindControl(name);
                if (found != null)
                {
                    return found;
                }

            }
        }
        return null;
    }

}

While compiling the above code in C# 2.0 a error a occurs

Cannot define a new extension method because the compiler required type ‘System.Runtime.CompilerServices.ExtensionAttribute’ cannot be found. Are you missing a reference to System.Core.dll?

Just make sure to include this code

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute { }
}

How to use it

Control ctrl = this.FindControl("TextBox1");

If you need to find number controls (Textbox1, Textbox2, ..) try this

for (int i = 0; i <=10; i++)
{
    Control ctrl = this.FindControl("TextBox" + i);
}

Leave a Reply