循环控制并检查值

时间:2015-03-08 08:46:15

标签: 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”加下划线蓝色,我收到错误:'value'不是'System.Windows.Forms.Control'的成员。

如何使这个工作?

2 个答案:

答案 0 :(得分:1)

您需要将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

答案 1 :(得分:1)

您已将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."))
相关问题