For each statement

L

Lou

I have a panel control with buttons and labels
I want to loop through only the buttons so I do this

Dim btn As Button

For Each btn In FlowPanelBottom.Controls

Next

I get an error that the control is a label control. Why is that when I am
only looping through button types?

Unable to cast object of type 'System.Windows.Forms.Label' to type



-Louie
 
C

Chris Mullins [MVP]

Change this to:

For Each c as Control in FlowPanelBottom.Controls

If c is Button then
// do button stuff here
end if

Next
 
B

boo

I have a panel control with buttons and labels
I want to loop through only the buttons so I do this

Dim btn As Button

For Each btn In FlowPanelBottom.Controls

Next

I get an error that the control is a label control. Why is that when I am
only looping through button types?

Unable to cast object of type 'System.Windows.Forms.Label' to type

-Louie

Dim btn As control

For Each btn In FlowPanelBottom.Controls
if typeof btn is button then
your commands here.
end if
Next
 
C

Cor Ligthert [MVP]

Lou,

I did not test it, but probably you don't have option strict in the top of
your program not set to ON.

Now it threath the button as a control (you are going through the collection
of controls).

For the rest see the other advices.

Cor
 
H

Herfried K. Wagner [MVP]

Chris Mullins said:
For Each c as Control in FlowPanelBottom.Controls

If c is Button then

I believe you wanted to type 'If TypeOf c Is Button Then' :).
 
C

Chris Mullins [MVP]

Herfried K. Wagner said:
I believe you wanted to type 'If TypeOf c Is Button Then' :).

Yup, that's exactly what I meant.

C# and VB.Net are so blurred for me, I can't ever keep the syntax
straight...
 

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