vb.net 无法将“System.Windows.Forms.Button”类型的对象转换为“System.Windows.Forms.TextBox”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13002128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to cast object of type 'System.Windows.Forms.Button' to type > 'System.Windows.Forms.TextBox'
提问by Renaud is Not Bill Gates
I wrote a function that empty all TextBox in my form:
我编写了一个函数来清空表单中的所有 TextBox:
Private Sub effacer()
For Each t As TextBox In Me.Controls
t.Text = Nothing
Next
End Sub
But I had this problem :
但我遇到了这个问题:
Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox'.
无法将“System.Windows.Forms.Button”类型的对象强制转换为“System.Windows.Forms.TextBox”。
I tried to add this If TypeOf t Is TextBox Thenbut I had the same problem
我试图添加这个,If TypeOf t Is TextBox Then但我遇到了同样的问题
回答by Tim Schmelter
The Controlscollection contains all controls of the form not only TextBoxes.
该Controls集合包含表单的所有控件,而不仅仅是 TextBox。
Instead you can use Enumerable.OfTypeto find and cast all TextBoxes:
相反,您可以使用Enumerable.OfTypefind 和 cast all 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
回答by SLaks
For Each t As TextBox In Me.Controls
This line right here tries to cast each control to TextBox.
You need to change that to As Control, or use Me.Controls.OfType(Of TextBox)()to filter the collection before iterating it.
此处的这一行尝试将每个控件强制转换为TextBox.
您需要将其更改为As Control,或用于Me.Controls.OfType(Of TextBox)()在迭代之前过滤集合。
回答by Vadzim Savenok
Here is a line of code that will clear all radioButtons from the groupBox, which is attached to the button_click:
这是一行代码,它将清除 groupBox 中的所有单选按钮,该 groupBox 附加到 button_click:
groupBoxName.Controls.OfType<RadioButton>().ToList().ForEach(p => p.Checked = false);
Use appropriate changes to adapt it to your needs.
使用适当的更改使其适应您的需要。

