Joan Venge Joan Venge - 3 months ago 15
C# Question

Finding a control on a Winforms using LINQ?

I am trying to find an elegant way to get controls on a Windows Forms form by name. For example:

MyForm.GetControl "MyTextBox"

...


But this has to make sure it goes through all the controls recursively.

What's the most elegant way to implement this using LINQ?

Answer

LINQ isn't necessarily best-suited to unknown-depth recursion; just use regular code...

public static Control FindControl(this Control root, string name) {
    if(root == null) throw new ArgumentNullException("root");
    foreach(Control child in root.Controls) {
        if(child.Name == name) return child;
        Control found = FindControl(child, name);
        if(found != null) return found;
    }
    return null;
}

with:

Control c = myForm.GetControl("MyTextBox");

Or if you don't like the recursion above:

public Control FindControl(Control root, string name) {
    if (root == null) throw new ArgumentNullException("root");
    var stack = new Stack<Control>();
    stack.Push(root);
    while (stack.Count > 0) {
        Control item = stack.Pop();
        if (item.Name == name) return item;
        foreach (Control child in item.Controls) {
            stack.Push(child);
        }
    }
    return null;
}