Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: Enumerating all controls on a Win Form

11 views
Skip to first unread message
Message has been deleted

bradbury9

unread,
Apr 25, 2013, 2:59:31 AM4/25/13
to
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);
}
}
}

Arne Vajhøj

unread,
Apr 26, 2013, 10:05:08 PM4/26/13
to
On 4/25/2013 2:59 AM, bradbury9 wrote:
> 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.
>
> 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


0 new messages