Ratty
Ratty

Reputation: 446

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 my code?

Aaron

Upvotes: 0

Views: 5644

Answers (2)

Joel Coehoorn
Joel Coehoorn

Reputation: 415765

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

Upvotes: 0

Tom Studee
Tom Studee

Reputation: 10452

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.

Upvotes: 2

Related Questions