Our Man in Bananas
Our Man in Bananas

Reputation: 5981

winforms vb 2008 textbox validation issue

I have vb 2008 Winforms application.

In my Branch form I have 11 textbox fields and I want to validate 8 of them, either mandatory, or required format such as UK postcode, UK tel nos etc.

My issue now is that when the validation starts, it is validating the last text field first ( or seems to be)

here is my code

For Each oCtrl As Control In Me.Controls
    If TypeOf oCtrl Is TextBox Then
        oCtrl.Focus()
        If Validate() = False Then

            Exit Sub

        End If
    End If
Next

what's wrong please?

Upvotes: 0

Views: 466

Answers (1)

tinstaafl
tinstaafl

Reputation: 6948

what's wrong please?

The controls collection isn't sorted or grouped. Your loop will access them in whatever order the collection has them.

Without more code it's hard to say how to fix it. However a tip may be in order. Use the same handler to handle the validate event for each textbox. This way you can keep the user at that textbox until the input is valid.

is it possible to add the items to the collection in the order of their tab indexes on form Shown event, how would I do that please?

A List(Of TextBox) and a custom sorter would probably be the way to go

Dim AllTB As New List(Of TextBox)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    AllTB.AddRange(Me.Controls.OfType(Of TextBox))
    AllTB.Sort(Function(x, y) x.TabIndex.CompareTo(y.TabIndex))
End Sub

To loop through the textboxes use:

For Each tb As TextBox in AllTB

Because the TextBoxes are in the list by reference you can get or set any of the properties in the textboxes and any changes, will be reflected on your form. You could also use sequential names for the textboxes, tag property, etc. and sort by that.

Upvotes: 1

Related Questions