Cycle through components on a form at run time

A

Andrew

I have a need to cycle through the compoents on the form in my program at
run time to check for the existence of certain components.

I do *not* mean the Controls via the form.Controls array, I want the non
visual components.

I know the components are not technically part of the form but there must be
a way to access the list of them.

Does anyone know how?

Thanks
 
O

Oliver Sturm

Hello Andrew,
I have a need to cycle through the compoents on the form in my program at
run time to check for the existence of certain components.

The most reliable way to do this would involve using Reflection. For
instance, this snippet outputs the name of each Component that is stored
in a private field in the Form derived class (which is true at least for
all the components the VS designer handles):

Type formType = this.GetType( );
FieldInfo[] fields = formType.GetFields( BindingFlags.Instance |
BindingFlags.NonPublic);
foreach (FieldInfo field in fields) {
if (typeof(Component).IsAssignableFrom(field.FieldType))
Debug.WriteLine(field.Name);
}

For your purpose I guess you'd have to modify this a bit - for example,
use field.GetValue() to retrieve a reference to the actual component
instance or something like that.


Oliver Sturm
 
A

Andrew

Thanks Oliver,

I was begining to think this would be the only way. Its a pity they didn't
add a components array like in Delphi.
 
O

Oliver Sturm

Hello Andrew,
I was begining to think this would be the only way. Its a pity they
didn't add a components array like in Delphi.

Well, yes... but then, with Reflection being as good as it is in .NET, it
not necessary to anticipate every such requirement at an early stage.
Those five or so lines of code in a GetComponents(Form form) method and
you're done.


Oliver Sturm
 

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