遍历窗体中的所有控件,甚至是在GroupBoxes中的控件。

23

我想要为表单上的所有文本框添加事件:

foreach (Control C in this.Controls)
{
    if (C.GetType() == typeof(System.Windows.Forms.TextBox))
    {
        C.TextChanged += new EventHandler(C_TextChanged);
    }
}

问题在于它们存储在多个GroupBox中,我的循环看不到它们。我可以逐个循环每个GroupBox的控件,但是否可能在一个循环中简单地完成所有操作?

1
你可以使用递归循环来完成它。 - jac
我已经为此制作了一个API提案:为控件添加Descendants属性。如果你喜欢,请在github.com/dotnet/winforms上点赞。 - Olivier Jacot-Descombes
9个回答

39

Controls 集合包含表单和容器控件的直接子级。为了获取所有控件,您需要遍历控件树并递归应用此操作。

private void AddTextChangedHandler(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if (c.GetType() == typeof(TextBox)) {
            c.TextChanged += new EventHandler(C_TextChanged);
        } else {
            AddTextChangedHandler(c);
        }
    }
}

注意:该表单(间接地)派生自Control,并且所有控件都有一个Controls集合。因此,您可以在表单中这样调用方法:
AddTextChangedHandler(this);

一个更通用的解决方案是创建一个扩展方法,将一个操作递归地应用于所有控件。在一个静态类(如WinFormsExtensions)中添加这个方法:

public static void ForAllControls(this Control parent, Action<Control> action)
{
    foreach (Control c in parent.Controls) {
        action(c);
        ForAllControls(c, action);
    }
}

静态类的命名空间必须是“可见的”,即如果它在另一个命名空间中,则需要添加适当的using声明。
然后您可以像这样调用它,其中this是窗体;您也可以将this替换为需要受影响的嵌套控件的窗体或控件变量:
this.ForAllControls(c =>
{
    if (c.GetType() == typeof(TextBox)) {
        c.TextChanged += C_TextChanged;
    }
});

21
几个简单的通用工具使这个问题非常直接。我们可以创建一个简单的方法,遍历整个控件树,返回其所有子项、所有子项的子项等等的序列,覆盖所有控件,而不仅仅是固定深度。我们可以使用递归,但通过避免递归,它将表现更好。
public static IEnumerable<Control> GetAllChildren(this 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;
    }
}

使用这个方法,我们可以获取所有的子元素,过滤出我们需要的类型,然后非常容易地附加处理程序:very

foreach(var textbox in GetAllChildren().OfType<Textbox>())
    textbox.TextChanged += C_TextChanged;

我不知道递归有另一种解决方案。学无止境。 - Walter Stabosz

7

试试这个

AllSubControls(this).OfType<TextBox>().ToList()
    .ForEach(o => o.TextChanged += C_TextChanged);

其中 AllSubControls 是

private static IEnumerable<Control> AllSubControls(Control control)
    => Enumerable.Repeat(control, 1)
       .Union(control.Controls.OfType<Control>()
                              .SelectMany(AllSubControls)
             );

LINQ很棒!

2

我还没有见过有人使用linq和/或yield,所以让我们开始吧:

public static class UtilitiesX {

    public static IEnumerable<Control> GetEntireControlsTree(this Control rootControl)
    {
        yield return rootControl;
        foreach (var childControl in rootControl.Controls.Cast<Control>().SelectMany(x => x.GetEntireControlsTree()))
        {
            yield return childControl;
        }
    }

    public static void ForEach<T>(this IEnumerable<T> en, Action<T> action)
    {
        foreach (var obj in en) action(obj);
    }
}

您可以随心所欲地使用它:

someControl.GetEntireControlsTree().OfType<TextBox>().ForEach(x => x.Click += someHandler);

2
我知道这是一个较旧的话题,但我认为http://backstreet.ch/coding/code-snippets/mit-c-rekursiv-durch-form-controls-loopen/中的代码片段是解决此问题的巧妙方法。它使用了ControlCollection的扩展方法。
public static void ApplyToAll<T>(this Control.ControlCollection controlCollection, string tagFilter, Action action)
{
    foreach (Control control in controlCollection)
    {
        if (!string.IsNullOrEmpty(tagFilter))
        {
            if (control.Tag == null)
            {
                control.Tag = "";
            }

            if (!string.IsNullOrEmpty(tagFilter) && control.Tag.ToString() == tagFilter && control is T)
            {
                action(control);
            }
        }
        else
        {
            if (control is T)
            {
                action(control);
            }
        }

        if (control.Controls != null && control.Controls.Count > 0)
        {
            ApplyToAll(control.Controls, tagFilter, action);
        }
    }
}

现在,要将事件分配给所有的文本框控件,您可以编写如下语句(其中“this”是表单):
this.Controls.ApplyToAll<TextBox>("", control =>
{
    control.TextChanged += SomeEvent
});

您可以选择按标签过滤控件。


1

正如您所述,您需要深入了解表单中的每个元素,这不幸意味着需要使用嵌套循环。

在第一个循环中,遍历每个元素。如果该元素为GroupBox类型,则需要在继续之前遍历组合框内的每个元素;否则像往常一样添加事件。

您似乎对C#有了不错的掌握,因此我不会给您任何代码,纯粹是为了确保您开发出涉及问题解决的所有重要概念 :)


1

您只能使用窗体集合循环遍历Windows表单中的打开表单,例如为所有打开的表单设置Windows起始位置:

public static void setStartPosition()
        {
            FormCollection fc = Application.OpenForms;

            foreach(Form f in fc)
            {
                f.StartPosition = FormStartPosition.CenterScreen;
            }
        }

1

由于“将事件添加到文本框”的问题已经得到解答,因此我提供一些解释并提供使用for循环的迭代替代方案。


问题:

  • 无法获取容器内的控件。


解决方案:

  • 为了检索容器内的控件,您必须指定包含要访问的控件的容器。 因此,您的循环必须检查容器内的控件。
    否则,您的循环将无法找到容器内的控件。

i.e:

foreach (Control control in myContainer.Controls)
{
   if (control is TextBox) { /* Do Something */ }
}
  • 如果您有多个容器:
    最初迭代容器。
    然后迭代容器内的控件(在最初迭代中找到的容器)。


如何使用for循环的伪代码示例:

    /// <summary> Iterate Controls Inside a Container using a for Loop. </summary>
    public void IterateOverControlsIncontainer()
    {
        // Iterate Controls Inside a Container (i.e: a Panel Container)
        for (int i = 0; i < myContainer.Controls.Count; i++)
        {
            // Get Container Control by Current Iteration Index
            // Note:
            // You don't need to dispose or set a variable to null.
            // The ".NET" GabageCollector (GC); will clear up any unreferenced classes when a method ends in it's own time.
            Control control = myContainer.Controls[i];

            // Perform your Comparison
            if (control is TextBox)
            {
                // Control Iteration Test.
                // Shall Display a MessageBox for Each Matching Control in Specified Container.
                MessageBox.Show("Control Name: " + control.Name);
            }
        }
    }

很好的解释。干得好! - user2225495

0

更新的答案:

我需要禁用表单中的所有控件,包括分组框。这段代码有效:

    private void AlterControlsEnable(bool ControlEnabled)
    {
        foreach (Control i in Controls)
            i.Enabled = ControlEnabled;
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接