无法将类型为"System.Windows.Forms.Button"的对象强制转换为类型>'System.Windows.Forms.TextBox'

Ich*_*aki 1 vb.net

我写了一个函数,在我的表单中清空所有TextBox:

Private Sub effacer()
        For Each t As TextBox In Me.Controls
            t.Text = Nothing
        Next
    End Sub
Run Code Online (Sandbox Code Playgroud)

但我遇到了这个问题:

无法将类型为"System.Windows.Forms.Button"的对象强制转换为"System.Windows.Forms.TextBox".

我试图添加这个,If TypeOf t Is TextBox Then 但我遇到了同样的问题

Tim*_*ter 5

Controls集合包含表单的所有控件,而不仅仅是TextBoxes.

相反,你可以Enumerable.OfType用来查找和投射所有TextBoxes:

For Each txt As TextBox In Me.Controls.OfType(Of TextBox)()
    txt.Text = ""
Next
Run Code Online (Sandbox Code Playgroud)

如果你想以"老派"的方式做同样的事情:

For Each ctrl As Object In Me.Controls
    If TypeOf ctrl Is TextBox
        DirectCast(ctrl, TextBox).Text = ""
    End If
Next
Run Code Online (Sandbox Code Playgroud)