Enumerating all controls on a Win Form

R

Raymon

I want to enumerate all controls on a form and list them by their
names and types.
The form has all kinds of controls.
Aside from regular controls like textboxes and buttons the form has
containers which themselves have controls inside them.
There are also menustrip and toolstrip with their own items.
I can of course traverse the form's controls collection but that only
gives the top level controls.
This obviously has to be done recursively but I am stumped how to
do it.

Can anyone help?
Thanks.
 
B

bradbury9

El jueves, 25 de abril de 2013 07:05:38 UTC+2, Raymon escribió:
I want to enumerate all controls on a form and list them by their

names and types.

The form has all kinds of controls.

Aside from regular controls like textboxes and buttons the form has

containers which themselves have controls inside them.

There are also menustrip and toolstrip with their own items.

I can of course traverse the form's controls collection but that only

gives the top level controls.

This obviously has to be done recursively but I am stumped how to

do it.



Can anyone help?

Thanks.

The Control class just the same as the Form class has a Controls collection..

List<string> controlTypes = new List<string>();

listButton_Click(){
foreach(Control ctrl in this.Controls){ // Loop through Form.Controls
doRecursive(ctrl);
}
}

private void doRecursive(Control formControl){
controlTypes.Add(formControl.GetType().ToString());
if(formControl.Controls != null){ // Loop through Control.Controls
foreach(Control ctrl in formControl.Controls){
doRecursive(ctrl);
}
}
}
 
A

Arne Vajhøj

El jueves, 25 de abril de 2013 07:05:38 UTC+2, Raymon escribió:

The Control class just the same as the Form class has a Controls collection.

List<string> controlTypes = new List<string>();

listButton_Click(){
foreach(Control ctrl in this.Controls){ // Loop through Form.Controls
doRecursive(ctrl);
}
}

private void doRecursive(Control formControl){
controlTypes.Add(formControl.GetType().ToString());
if(formControl.Controls != null){ // Loop through Control.Controls
foreach(Control ctrl in formControl.Controls){
doRecursive(ctrl);
}
}
}

That is the way to recurse through Controls.

I just want to add a little warning. Be very careful if
you also try to recurse on properties that are Control or subclass
of Control. Parent and other properties point back with the risk
of entering an infinite loop.

Guess who recently was hit by that.

:)

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top