循环遍历控件并检查值

  • 本文关键字:遍历 控件 循环 vb.net
  • 更新时间 :
  • 英文 :


其中,我的表单中几乎没有NumericUpDown控件,我想检查此控件的值是否在1到50之间输入。

喜欢这个:

    ''general check
    Dim errors As String = ""
    For Each ctrl As Control In Me.Controls
        If TypeOf ctrl Is NumericUpDown Then
            '' error here
            If ctrl.value < 1 Or ctrl.Value > 50 Then
                errors += ctrl.Name + " is out of range." + Environment.NewLine
            End If
        End If
    Next

使用此代码"ctrl.value"下划线为蓝色,我得到错误:"值"不是"System.Windows.Forms.Control"的成员。

如何让它工作?

您需要

ctrl转换为类型 NumericUpDown,因为Control没有.Value属性。您可以使用 TryCast .它尝试将控件转换为正确的类型,如果失败,则返回 Nothing

    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

您已经将ctrl定义为Control,并且只询问它是否是NumericUpDown。你还没有把它投到一个。

我的首选方法是使用 LINQ。

Dim errors = String.Join(Environment.NewLine, _
    Me.Controls _
        .OfType(Of NumericUpDown)() _
        .Where(Function (x) x.Value < 1 OrElse x.Value > 50) _
        .Select(Function (x) ctrl.Name + " is out of range."))

最新更新