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

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

    Try this

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

    where AllSubControls is

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

    LINQ is great!

提交回复
热议问题