Find controls by name in C#

This example shows how you can search a control hierarchy to find controls by name in C#. The following FindControl function does all of the work. It takes as parameters the parent control to check first and the name to find. It searches the parent control and its descendants.

// Recursively find the named control.
private Control FindControl(Control parent, string name)
    // Check the parent.
    if (parent.Name == name) return parent;

    // Recursively search the parent's children.
    foreach (Control ctl in parent.Controls)
        Control found = FindControl(ctl, name);
        if (found != null) return found;

    // If we still haven't found it, it's not here.
    return null;

The function starts by checking the parent to see if it has the target name. If it doesn’t have the right name, the function calls itself recursively to check each of the parent’s child controls. That searches the children and any controls they contain. For example, the label2 control in the example program is contained inside groupBox1.

If none of the recursive calls to FindControl finds the right control, then it’s not within the parent’s control hierarchy so the function returns null.

Note that this version makes a case-sensitive search for the named control. You can change the code to perform a case-insensitive search if you like.

(Also note that the form itself is a control, so you can search for it and search its control hierarchy.)

This entry was posted in controls and tagged , , , , , , , , . Bookmark the permalink.

3 Responses to Find controls by name in C#

  1. asddas says:

    How to call it?

    Calling is showing error

    • RodStephens says:

      To see the example program in action, you should download it and run it.

      In your program you should be able to pass it an ancestor such as the form and the name of the control you want to find.

  2. Ello says:
    static IEnumerable GetAllControls(Control control)
        return control.Controls.Cast()
            .SelectMany(ctrl => GetAllControls(ctrl))
            .Concat(new Control[] {control});

    With the method above, you can use any of the LINQ methods to filter out and process whatever you want

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.