Aimad MAJDOU Aimad MAJDOU - 1 year ago 127 Question

Unable to cast object of type 'System.Windows.Forms.Button' to type > 'System.Windows.Forms.TextBox'

I wrote a function that empty all TextBox in my form:

Private Sub effacer()
For Each t As TextBox In Me.Controls
t.Text = Nothing
End Sub

But I had this problem :

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

I tried to add this
If TypeOf t Is TextBox Then
but I had the same problem

Answer Source

The Controls collection contains all controls of the form not only TextBoxes.

Instead you can use Enumerable.OfType to find and cast all TextBoxes:

For Each txt As TextBox In Me.Controls.OfType(Of TextBox)()
    txt.Text = ""

If you want to do the same in the "old-school" way:

For Each ctrl As Object In Me.Controls
    If TypeOf ctrl Is TextBox
        DirectCast(ctrl, TextBox).Text = ""
    End If
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download