Get ALL controls on a Form

  • Thread starter Thread starter DraguVaso
  • Start date Start date
D

DraguVaso

Hi,

Is there actually a way to get ALL the Controls on a Form? While using the
ControlCollection, it only returns the Controls that are directly on the
Form, not the controls that are on a (TableLayout)Panel etc.

I never found something like that, but it just would be nice in my opinion
:-)

Thanks,

Pieter
 
private ControlCollection res = new ControlCollection();
public void GetControls(Control parent)
{
if (! parent is Form)
{
res.Add(parent);
}

foreach(Control c in parent.Controls)
{
GetControls(c);
}
}
 
Hi,
you can use following code snippet.

foreach (Control ctr in this.Controls)
{
if (ctr.HasChildren) // Check for Containder Control
{
//Controls on other control (e.g Panel)
}
}

Hope this will solve your problem

Prasad.
 
Hi,

Is there actually a way to get ALL the Controls on a Form? While
using the ControlCollection, it only returns the Controls that are
directly on the Form, not the controls that are on a
(TableLayout)Panel etc.


You could use a recursive procedure.

private sub GetControls(Control ctlParent, ref ArrayList al)
{
al.Add(ctlParent);
foreach(Control ctlChild in ctlParent)
GetControls(ctlChild, ref al);
}

Not tested, my development PC is off at the moment but something like
that should do it. Call it by setting up a new ArrayList and starting
with the Windows Form. If it doesn't recognise the Form as a control
you would need to start with:

private sub GetAllControls()
{
ArrayList al = new ArrayList();
foreach(Control ctl in frmMain)
GetControls(ctl, ref al);
}
 
Pieter
Is there actually a way to get ALL the Controls on a Form? While using the
ControlCollection, it only returns the Controls that are directly on the
Form, not the controls that are on a (TableLayout)Panel etc.
Roughly done
\\\
Showall(me)
Private Sub ShowAll(ByVal parentCtr As Control)
For Each ctr As Control In parentCtr.Controls
Console.Write(ctr.name)
ShowAll(ctr)
Next
End Sub
///
I hope this helps,

Cor
 
Thanks guys, I guess recursion will indeed be the only solution for this. I
think it's kind of weird there isn't a Collection that returns everything on
a form, but so be it, hehe :-)

Pieter
 
DraguVaso said:
Is there actually a way to get ALL the Controls on a Form? While using the
ControlCollection, it only returns the Controls that are directly on the
Form, not the controls that are on a (TableLayout)Panel etc.

\\\
Private Sub RecurseControls(ByVal ctr As Control)
Debug.WriteLine(ctr.Name)
If ctr.HasChildren Then
For Each c As Control In ctr.Controls
RecurseControls(c)
Next c
End If
End Sub
..
..
..
RecurseControls(Me)
///
 
Back
Top