How to access find all controls and all components

2019-08-05 03:36发布

问题:

I have a window form which contain some Controls an some Components ( like DataTable, XPCollection etc). I would like find all Control Names and Component Names which used into this form.

回答1:

You could do,

List<string> ctrlNames = new List<string>();
FIndAllCtrls(ctrlNames , this.Controls);

private void FIndAllCtrls(ctrlNames, ControlCollection ctrlColl)
{
   foreach(Control ctrl in ctrlColl)
   {
      ctrlNames.Add(ctrl.Name);
      if(ctrl.Controls.Count > 0)
         FIndAllCtrls(ctrlNames, ctrl.Controls);
   }
}


回答2:

    IEnumerable<Control> EnumControls(Control top)
    {
        Queue<Control> todo = new Queue<Control>();
        todo.Enqueue(top);

        while (todo.Count > 0)
        {
            Control c = todo.Dequeue();

            yield return c;
            foreach (Control ch in c.Controls)
                todo.Enqueue(ch);
        }
    }


回答3:

it is explained in this node: Find components on a windows form c# (not controls) It looks there is only way via Reflection available.