Odd 'Unable to cast object of type..' error

delstar

Well-known member
Joined
Jun 9, 2006
Messages
59
Programming Experience
1-3
I was playing around, trying to see if you could change a bunch of labels in a container, and came up with the following code :

VB.NET:
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
              As System.EventArgs) Handles Button1.Click
        Dim control As ControlCollection = Me.Panel1.Controls

        For Each lbl As Object In control
            lbl.Text = "hi"
        Next


    End Sub
End Class

I tried running the code, but it threw an exception at :
"Dim control As ControlCollection = Me.Panel1.Controls"
saying :
"Unable to cast object of type 'ControlCollection' to type 'ControlCollection'"

Anyone able to explain what's going on here? Incidently, it works if I don't use the container.
 
Nevermind. My bad. Didn't realize there were two different ControlCollection types. The one that control is defined as and the one i was was trying to set it equal to came from two different namespaces. Redefined my control to match, and everything works fine now. Until I break it again, that is.
 
An easier way would be to access the containers control collection directly, and rather than casting to object which is slow, cast to every controls base class which is 'control'

VB.NET:
For Each Ctrl as control in panel1.controls
ctrl.text = "Hello"
Next
 
Back
Top