Recursively notify child controls via C#

前端 未结 4 1998
执笔经年
执笔经年 2020-12-18 08:56

I have a form MainForm which is a Windows Forms form that contains many child controls. I want to call one function on MainForm that notifies all o

4条回答
  •  爱一瞬间的悲伤
    2020-12-18 09:27

    foreach (Control ctrl in this.Controls)
    {
        // call whatever you want on ctrl
    }
    

    If you want access to all controls on the form, and also all the controls on each control on the form (and so on, recursively), use a function like this:

    public void DoSomething(Control.ControlCollection controls)
    {
        foreach (Control ctrl in controls)
        {
            // do something to ctrl
            MessageBox.Show(ctrl.Name);
            // recurse through all child controls
            DoSomething(ctrl.Controls);
        }
    }
    

    ... which you call by initially passing in the form's Controls collection, like this:

    DoSomething(this.Controls);
    

提交回复
热议问题