I'm writing code to iterate through all controls on a form. This seemed pretty straight forward except that the Form.Controls collection does not include controls that are contained by other controls.

Ok, so I tried testing to see if each ctl is ContainerControl, and if so, recursively iterating through the controls in that container control.

Ok, but it turns out the GroupBox control does not derive from ContainerControl. It derives directly from Control.

Is there any generic way for my code to determine if a given control contains other controls? I assumed there would be a base type or interface that would do this but that doesn't seem to be the case.

有帮助吗?

解决方案

You can use the Control.HasChildren property:

True if this control has child controls in its collection.

if (ctl.HasChildren)
{
    // true, if ctl has controls in it
}

其他提示

    List<Control> AllFormsControl = new List<Control>();
    public void InitContolList(Control nControl)
    {
        if (nControl.Controls.Count > 0)
        {
            foreach (Control item in nControl.Controls)
            {
                 InitContolList(item);
                AllFormsControl.Add(item);
            }

        }
      // Optional
      //AllFormsControl.Add(nControl);
    }

Then you may run:

    InitControlList(this);

Good luck.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top