按Taborder循环控制

时间:2015-03-08 20:14:48

标签: vb.net

今天我要求帮助循环遍历窗体上的所有控件以便引用NumericUpDown' s这是一个公认的答案:

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

后来通过开发我的程序,我意识到NumericUpDown被列在(对我来说)未知顺序中,这不是想要的结果。
我希望/需要NumericUpDown将按Tab键顺序的索引进行循环。

任何建议如何通过注释linq不可用,因为此应用程序是针对.NET framework 2.0的。

1 个答案:

答案 0 :(得分:1)

假设您在设计器中定义了三个NumericUpDown控件并命名为numericUpDown1,numericUpDown2,numericUpDown3 现在在表单

中声明一个全局变量
Public Class MyForm

    Dim numUpDnList(2) As NumericUpDown
    ....

然后在你的代码中(可能在表单加载事件中)按照你需要的顺序在数组变量中添加它们

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

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

End Sub

此时,无论何时需要枚举这些控件,代码都非常简单

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

还有另一种方法可以使用TabOrder之后的GetNextControl方法循环控件集合。

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