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

后端 未结 9 1147
囚心锁ツ
囚心锁ツ 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:51

    Haven't seen anyone using linq and/or yield so here goes:

    public static class UtilitiesX {
    
        public static IEnumerable GetEntireControlsTree(this Control rootControl)
        {
            yield return rootControl;
            foreach (var childControl in rootControl.Controls.Cast().SelectMany(x => x.GetEntireControlsTree()))
            {
                yield return childControl;
            }
        }
    
        public static void ForEach(this IEnumerable en, Action action)
        {
            foreach (var obj in en) action(obj);
        }
    }
    

    You may then use it to your heart's desire:

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

提交回复
热议问题