Looping through textboxes in groupbox give odd results
I have the following code:
For Each control2 As Control In GroupBox3.Controls
If TypeOf control2 Is TextBox Then
Dim txt2 As TextBox = TryCast(control2, TextBox)
If counter > totalBoxes Then
totalBoxes += 1
txt2.Text = grade(totalBoxes)
End If
End If
Next
What I am doing is looping through each textbox in groupbox3. Then checking if the counter(total number of grades that are inputted in the form) are greater than the totalBoxes(which is set to 0) and finally I am putting the actual grade(A,B,C,D) into the textbox. The problem is that it is starting the loop at textbox 8(I have 10 textboxes) for some reason and going from there. Does anyone know what the problem is with 开发者_C百科my code?
Aaron
Well, the name of your textbox has no relation to its index in the .Controls collection of its parent.
One thing you could do is set the .tag property of each of your controls to the index you'd like to pass into your grade function.
textbox1.Tag = 1
textbox2.Tag = 2
...
That way you don't have to worry about which order the textboxes are in while iterating.
For Each box As TextBox In GroupBox3.Controls.OfType(Of TextBox).OrderBy(Function(t) t.Name)
If counter > totalBoxes Then
totalBoxes += 1
box.Text = grade(totalBoxes)
End If
Next box
精彩评论