How to get all children of a parent control?

前端 未结 4 1075
长发绾君心
长发绾君心 2020-12-03 15:03

I\'m looking for an code example how to get all children of parent control.

I have no idea how do it.

foreach (Control control in Controls)
{
  if (         


        
4条回答
  •  自闭症患者
    2020-12-03 15:24

    If you only want the immediate children, use

    ...
    var children = control.Controls.OfType();
    ...
    

    If you want all controls from the hierarchy (ie, everything in the tree under a certain control), use a pretty simple data-recursive method:

        private IEnumerable GetControlHierarchy(Control root)
        {
            var queue = new Queue();
    
            queue.Enqueue(root);
    
            do
            {
                var control = queue.Dequeue();
    
                yield return control;
    
                foreach (var child in control.Controls.OfType())
                    queue.Enqueue(child);
    
            } while (queue.Count > 0);
    
        }
    

    Then, you might use something like this in a form:

        private void button1_Click(object sender, EventArgs e)
        {
            /// get all of the controls in the form's hierarchy in an IEnumerable<>
            foreach (var control in GetControlHierarchy(this))
            {
                /// do something with this control
            }
        }
    

提交回复
热议问题