Traversing Controls

E

elziko

I have a class ("ClassB") that inherits from 'ClassA' which inherist
from UserControl.

I then put ClassB onto a form. Is it then possible to tracerse all the
controls on the form that inherit from ClassA.

I would expect the following code to work... bring up ClassB from the
collection.

For Each component as ClassA in Form1.Controls
'this should give any control that is based on ClassA
Next

However, I get the following exception:

"Specified cast is not valid"

Is this not possible? I could have several different classes, all
inheriting from ClassA. I dont know what these classes will be until
run-time so I need to traverse by base class.

TIA
 
H

Herfried K. Wagner [MVP]

elziko said:
I have a class ("ClassB") that inherits from 'ClassA' which inherist
from UserControl.

I then put ClassB onto a form. Is it then possible to tracerse all the
controls on the form that inherit from ClassA.

I would expect the following code to work... bring up ClassB from the
collection.

For Each component as ClassA in Form1.Controls
'this should give any control that is based on ClassA
Next

\\\
For Each component As Control In Form1.Controls
If TypeOf component Is ClassA Then
DirectCast(component, ClassA).<...> = ...
End If
Next component
///
 
C

Chris Dunaway

For Each component as ClassA in Form1.Controls
'this should give any control that is based on ClassA
Next

That will iterate through ALL the controls on Form1 regardless of what type
they are. If one of them happens NOT to be a ClassA, then the cast will
fail.

You could try something like the following, but there are also plenty of
examples on this newsgroup:

For Each component As Control In Form1.Controls
If component Is ClassA Then
'Do something with component here
End If
Next


--
Chris

dunawayc[AT]sbcglobal_lunchmeat_[DOT]net

To send me an E-mail, remove the "[", "]", underscores ,lunchmeat, and
replace certain words in my E-Mail address.
 

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