Loop through all controls of a Form, even those in GroupBoxes

后端 未结 9 1125
囚心锁ツ
囚心锁ツ 2020-11-29 05:17

I\'d like to add an event to all TextBoxes on my Form:

foreach (Control C in this.Controls)
{
    if (C.GetType() == typeof(System.Windows.Forms         


        
9条回答
  •  隐瞒了意图╮
    2020-11-29 05:49

    A few simple, general purpose tools make this problem very straightforward. We can create a simple method that will traverse an entire control's tree, returning a sequence of all of it's children, all of their children, and so on, covering all controls, not just to a fixed depth. We could use recursion, but by avoiding recursion it will perform better.

    public static IEnumerable GetAllChildren(this Control root)
    {
        var stack = new Stack();
        stack.Push(root);
    
        while (stack.Any())
        {
            var next = stack.Pop();
            foreach (Control child in next.Controls)
                stack.Push(child);
            yield return next;
        }
    }
    

    Using this we can get all of the children, filter out those of the type we need, and then attach the handler very easily:

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

提交回复
热议问题