Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET For each enumerates incorrectly

I have the following code:

    For Each t As TabPage In Me.TabControl1.TabPages
        For Each p As Panel In t.Controls
            Dim sText As String = p.Name
            If modStrings.Has(sText, u) Then
                m_PrevPanel = p
                p.Parent = Me.pnlMain
                Return
            End If
        Next
    Next

But sometimes in the line

 For Each p as Panel in t.Controls

I get the error

"The object of the type SystemWindows.Forms.Button can not be cast to System.Windows.Forms.Panel".

I don't see why it would try to include a button in the "p as Panel" enumeration. Does anybody see what might go wrong here?

like image 433
tmighty Avatar asked Mar 26 '26 18:03

tmighty


2 Answers

Because you have a button on the TabPage controls collection.

Try filtering it:

For Each p As Panel In t.Controls.OfType(Of Panel)()

Next
like image 54
LarsTech Avatar answered Mar 30 '26 08:03

LarsTech


The enumeration doesn't work as you would suspect. This line:

For Each p As Panel In t.Controls

Doesn't filter the controls by only the panel objects, it return all the controls and tries to coerce them into Panel types - which will fail as soon as it find a control that is not a panel

You need to just an an extra check to make sure the control is a panel

    For Each ctl As Control In Me.Controls
        If ctl.GetType() Is GetType(Panel) Then
            Dim p As Panel = CType(ctl, Panel)

        End If
    Next

It would be nice if the compiler picked this up to be honest as it can be a common runtime error

like image 45
Matt Wilko Avatar answered Mar 30 '26 09:03

Matt Wilko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!