1

我有一个 Windows 窗体应用程序。

Windows 窗体由几个元素组成。我可以通过他们的名字联系到他们每个人。(例如:textbox1.Text)

我可以获取集合中的所有表单元素吗?

4

3 回答 3

3

You can use the method below to traverse a tree and get all of the child controls (at all depths) below any control.

public static IEnumerable<Control> GetAllControls(Control root)
{
    var stack = new Stack<Control>();
    stack.Push(root);

    while (stack.Any())
    {
        var next = stack.Pop();
        foreach (Control child in next.Controls)
            stack.Push(child);

        yield return next;
    }
}

You can then pass in the form as the root to get all of the controls in that form in a single sequence. Use ToList if you want them all in a List instead.

If you want to filter out only the controls of a particular type, use OfType:

var textboxes = GetAllControls(someForm).OfTYpe<Textbox>();
于 2013-09-05T18:51:21.697 回答
0

在文件后面的代码中尝试 this.Controls,它应该会为您提供所有控件的列表。

于 2013-09-05T18:46:31.807 回答
0

使用this.Controls(或更正式地说Control.Controls:)

要获取所有TextBox控件,请使用以下命令:

this.Controls.OfType<Control>().Where(x => x is TextBox);

这只会获得顶级项目。如果你需要更深入(cue inception),你需要做一些递归。

于 2013-09-05T18:48:27.030 回答