Finding a control on a Winforms using LINQ?

后端 未结 4 2020
灰色年华
灰色年华 2020-12-09 13:14

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

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 13:28

    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;
    }
    

提交回复
热议问题