Reputation: 2084
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 :
Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.TextBox'.
I tried to add this If TypeOf t Is TextBox Then
but I had the same problem
Upvotes: 1
Views: 9416
Reputation: 940
Here is a line of code that will clear all radioButtons from the groupBox, which is attached to the button_click:
groupBoxName.Controls.OfType<RadioButton>().ToList().ForEach(p => p.Checked = false);
Use appropriate changes to adapt it to your needs.
Upvotes: 0
Reputation: 460108
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 = ""
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
Upvotes: 5
Reputation: 887453
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.
Upvotes: 2