Clearing multiple text fields
I tried searching for a solution, but couldn't find anything, so if I am re-asking a common question, don't beat me too badly.
For a class, I have to create a form that allows someone to enter in the names of six students, as well as five test scores each. It also averages the scores, and displays them in a label.
What I am wondering is if there is a way to clear the text from all 36 text fields, as well as the 6 labels without having to do everything individually?
I could certainly go through, and write out txtField1.text = String.Empty 36 times, but it seems there would be a more elegant solution.
Also, if there is a way to do so, would the same would apply for putting the data entered into an array, or saving it to a file?
Re: Clearing multiple text fields
You can use a loop of some sort, but exactly how to do it depends on how your controls are laid out and/or named. For instance, you had TextBoxes named TextBox1 to TextBox36 then you could do this:
vb.net Code:
For n = 1 To 36
Me.Controls("TextBox" & n).ResetText()
Next
It's not really a good idea to use names like that though. Another option would be to have your controls in a TableLayoutPanel and then use nested loops to work through it column by column, row by row. As a last resort, you can just create your own array or collection and then loop through that.
Re: Clearing multiple text fields
I was just using txtField1 as an example.
I will try out your suggestion, though, and see how it goes. Thanks!
Re: Clearing multiple text fields
You can loop through the TextBox controls used in the form dynamically and set it to blank value
vb Code:
For Each myControls In Me.Controls
If TypeOf myControls Is TextBox Then
myControls.Text = String.Empty
End If
Next
same way, you can check the labels using "Label" instead of TextBox
Hope this helps
Re: Clearing multiple text fields
try this:
vb Code:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim textboxes() As TextBox = Me.Controls.OfType(Of TextBox).ToArray
textboxes = Array.ConvertAll(textboxes, AddressOf clearTextBox)
End Sub
Private Function clearTextBox(ByVal tb As TextBox) As TextBox
tb.Text = ""
Return tb
End Function
End Class
Re: Clearing multiple text fields
Array.ConvertAll isn't really appropriate, given that there's no conversion occurring. If this is .NET 4.0 then lambda expressions don't have to return a value:
vb.net Code:
Dim textBoxes = Me.Controls.OfType(Of TextBox)().ToArray()
Array.ForEach(textBoxes, Sub(tb) tb.Clear())
If it's not .NET 4.0, or even if it is, you can just use a For Each loop:
vb.net Code:
For Each tb In Me.Controls.OfType(Of TextBox)()
tb.Clear()
Next
This assumes that you do want to clear every TextBox on the form of course.