Access ALL controls on a form?

  • Thread starter Thread starter Jamie Fraser
  • Start date Start date
J

Jamie Fraser

Hi,

Is there a way to loop through EVERY control on a form (whether they
are directly on the form, or contained within children of the form)?

I would like to access the size and location of every control - at the
moment im just using a loop as:

For Each c As Control In Me.Controls

For Each cChild As Control In c.Controls

<...>

but this obviously only goes down one level - I could use a whole
series of nested loops, but performance and code readability are quite
important - is there a way to access (or directly loop through) all
the controls?

Thanks

Jamie
 
You could use a recursive method,

The code is in C# but should be easily translated to VB.Net

private ArrayList GetAllChildControls(Control control)
{
ArrayList allControls = new ArrayList();

foreach(Control ctrl in control.Controls)
{
allControls.Add(ctrl);
allControls.AddRange(GetAllChildControls(ctrl))
}

return allControls;
}

To use it simple call

ArrayList allControls = GetAllChildControls(myForm);



Sijin Joseph
http://www.indiangeek.net
http://weblogs.asp.net/sjoseph
 
Jamie,

See this sample I have sand some days ago in another newsgroup.

I hope this helps?

Cor

\\\\
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
doset(Me)
'It starts on a top place, can be any place by instance
'a button event, however for all controls it has to start with Me
End Sub

Private Sub doSet(ByVal thisCtr As Control)
Dim ctr As Control
'a placeholder for the reference of the object is created
For Each ctr In thisCtr.Controls
'The first time each (parent)control on a form
If TypeOf ctr Is Label
'Look if the "Control" is a label
ctr.text = "This you can do for every property from that label
End if
doSet(ctr)
'check if the control has children and do for that the same
Next
End Sub
///
 
Back
Top