带有数字的'if'语句

时间:2014-07-13 11:16:59

标签: vb.net

我刚买了一个游泳池,我正在开发一个日志程序来测量每天的化学物质。我不会查看化学品应该是什么,而是将其构建到我的程序中,以下声明无法正常工作。即使我输入了6,Level Perfect仍显示在我的标签中:

If FCI__Free_Cholorine_ppmTextBox.Text < "1" Then
            lbfci.Text = "Level Too low"
        ElseIf FCI__Free_Cholorine_ppmTextBox.Text > "0" Then
            lbfci.Text = "Level Perfect"
        ElseIf FCI__Free_Cholorine_ppmTextBox.Text <= "4" Then
            lbfci.Text = "Level Perfect"
        ElseIf FCI__Free_Cholorine_ppmTextBox.Text > "4" Then
            lbfci.Text = "Level Too High"
        End If

2 个答案:

答案 0 :(得分:1)

理想情况下,您应首先使用Integer.TryParse方法将文本框的内容解析为整数,以便消除用户在文本框中输入数字时可能出现的任何错误。

' First initialize a String variable and Trim any whitespace
Dim s As String = FCI__Free_Cholorine_ppmTextBox.Text.ToString().Trim()
Dim num As Integer
    ' Integer.TryParse returns True if it has successfully parsed the String into an Integer
    If Integer.TryParse(s, num) Then
        If num > 4 Then
          lbfci.Text = "Level Too High"
        ElseIf num > 0 Then
          lbfci.Text = "Level Perfect"
        Else
          lbfci.Text = "Level Too low"
        End If
    Else
            lbfci.Text = "Not a number"
    End If

答案 1 :(得分:1)

将字符串转换为数字,然后使用if / elseif。检查顺序很重要

Private Sub FCI__Free_Cholorine_ppmTextBox_TextChanged(sender As Object, e As EventArgs) _
    Handles FCI__Free_Cholorine_ppmTextBox.TextChanged
    Dim lvl As Decimal
    If Decimal.TryParse(FCI__Free_Cholorine_ppmTextBox.Text, lvl) Then
        'the order of checking is important
        If lvl > 4 Then '5,6,7,etc.
            lbfci.Text = "Level Too High"
        ElseIf lvl > 0 Then '1,2,3,4
            lbfci.Text = "Level Perfect"
        Else
            lbfci.Text = "Level Too low"
        End If
    Else
        lbfci.Text = "Numbers only"
    End If
End Sub

这说明为什么字符串比较在这种情况下不是一个好主意

    Dim s As String = "10"
    Dim s1 As String = "4"
    If s > s1 Then
        Stop
    End If