[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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.)

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.