Find a control by its name in C#

The 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 version makes a case-sensitive search for the named control. You can change the code to perform a case-insensitive search if you like.

(Note also that the form itself is also a control so you can set its value using the name Form1.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.