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

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

    I know that this is an older topic, but would say the code snippet from http://backstreet.ch/coding/code-snippets/mit-c-rekursiv-durch-form-controls-loopen/ is a clever solution for this problem.

    It uses an extension method for ControlCollection.

    public static void ApplyToAll(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);
            }
        }
    }
    

    Now, to assign an event to all the TextBox controls you can write a statement like (where 'this' is the form):

    this.Controls.ApplyToAll("", control =>
    {
        control.TextChanged += SomeEvent
    });
    

    Optionally you can filter the controls by their tags.

提交回复
热议问题