Click here to Skip to main content
15,912,400 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I keep getting the following message,After implementing the my code.

'unable to cast object of type "system.windows.forms.buuton" to type
"system.windows.forms.TextBox"'

my code :
VB
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim NewTextBox As Boolean = True
        Try
            For Each txt As TextBox In Me.Controls
                If txt.Text = "" Then
                    NewTextBox = False
                End If
            Next
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub


Help Me Please?
Posted

1 solution

Me.Controls contains every control placed on the form. It will go through every control and try to implicitly cast it as a TextBox the way you've set it up. You need to rewrite your code to check whether it is a TextBox first.

VB
For Each ctrl As Control in Me.Controls
  If TypeOf ctrl Is TextBox Then
    If Ctype(ctrl, TextBox).Text = "" Then
      NewTextBox = False
    End If
  End If
Next


And none of that needs to be in a Try/Catch block. It should never throw an unhandled error.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900