I am trying to find an elegant way to get controls on a Windows Forms form by name. For example:
MyForm.GetControl \"MyTextBox\"
...
But t
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();
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;
}