Wine Too
Wine Too

Reputation: 4655

Loop through Controls by taborder

Today I asked for a help on looping through all Controls on form on order to reference NumericUpDown's and this was an accepted answer:

Dim errors As String = ""
For Each ctrl As Control In Me.Controls
    Dim num = TryCast(ctrl, NumericUpDown)
    If num IsNot Nothing AndAlso (num.Value < 1 OrElse num.Value > 50) Then
         errors += ctrl.Name + " is out of range." + Environment.NewLine
    End If
Next

Later by developing my program I realized that NumericUpDown's are listed in (for me) unknown order and this is not wanted result.
I would like/need that NumericUpDown's will be looped by index of tab order.

Any suggestion how to get that with remark that linq is not available because this application is targeted for .NET framework 2.0.

Upvotes: 1

Views: 1257

Answers (1)

Steve
Steve

Reputation: 216292

Suppose that you have three NumericUpDown controls defined in the designer and named numericUpDown1,numericUpDown2,numericUpDown3 Now declare a global variable in the form class

Public Class MyForm

    Dim numUpDnList(2) As NumericUpDown
    ....

Then in your code (possibly in the form load event) add them at the array variable in the order that you require

Protected Sub MyForm_Load(sender as Object, e as EventArgs) Handles Form.Load

      numUpDnList(0) = numericUpDown1
      numUpDnList(1) = numericUpDown3
      numUpDnList(2) = numericUpDown2

End Sub

At this point, whenever you need to enumerate these controls, the code is pretty simple

Dim errors As String = ""
For Each num In numUpDnList
    If (num.Value < 1 OrElse num.Value > 50) Then
         errors += num.Name + " is out of range." + Environment.NewLine
    End If
Next

There is also another way to loop over the Controls collection using the GetNextControl method that follows the TabOrder.

Dim errors as String
Dim ctrl = Me.GetNextControl(f, true)
while ctrl IsNot Nothing
    Dim num = TryCast(ctrl, NumericUpDown)
    If num IsNot Nothing AndAlso (num.Value < 1 OrElse num.Value > 50) Then
        errors += ctrl.Name + " is out of range." + Environment.NewLine
     End If        
     ctrl = f.GetNextControl(ctrl, true)
End While

Upvotes: 1

Related Questions