无法将“System.Windows.Forms.Button"类型的对象强制转换为类型 >'System.Windows.Forms.TextBox' [英] Unable to cast object of type 'System.Windows.Forms.Button' to type > 'System.Windows.Forms.TextBox'

查看:32
本文介绍了无法将“System.Windows.Forms.Button"类型的对象强制转换为类型 >'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
        Next
    End Sub

但是我遇到了这个问题:

But I had this problem :

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

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

我尝试添加此 If TypeOf t Is TextBox Then 但我遇到了同样的问题

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

推荐答案

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

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

相反,您可以使用 Enumerable.OfType 来查找和转换所有 TextBoxes:

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

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

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
Next

这篇关于无法将“System.Windows.Forms.Button"类型的对象强制转换为类型 >'System.Windows.Forms.TextBox'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆