【问题标题】:How to use Recursive Method in winforms c#如何在winforms c#中使用递归方法
【发布时间】:2014-02-12 03:30:12
【问题描述】:

我需要在我的表单中找到控件。在asp.net中我使用递归方法来做它。现在如何在winforms中做

public static Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
        return root;

    return root.Controls.Cast<Control>()
       .Select(c => FindControlRecursive(c, id))
       .FirstOrDefault(c => c != null);
}

任何想法..谢谢...

【问题讨论】:

标签: c# winforms methods


【解决方案1】:

每个控件都有一个Controls 属性,它实际上是一个ControlCollection。这个集合本身有一个方法Find(),它有两个参数。第一个参数是您要查找的控件的名称,第二个参数表示是否将所有子控件都包含在搜索中。

作为示例:

Control[] allButton1 = this.Controls.Find("button1", true);
// for your example
Control[] foundControls = this.Controls.Find(root.Name,true);

【讨论】:

    【解决方案2】:

    您可以在 win 表单中使用 root.Name 代替 root.ID

    【讨论】:

    • 在根参数中传递什么。如果我通过了它的显示错误
    • 你可以像这样传递表单对象:Form1 f=new Form1();控制 ctl=FindControlRecursive(f, "textBox1");
    猜你喜欢
    • 2012-05-04
    • 2014-12-19
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多