简体   繁体   中英

An 'if' statement with numbers

I just bought a pool, and I am developing a log program to measure the chemicals every day. Rather than looking up what the chemical is supposed to be, I will build it into my program, the below statement isn't working properly. Even if I put in a 6, Level Perfect still shows up in my label:

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

Ideally you should parse the contents of the textbox as an Integer first using the Integer.TryParse method in order to cut out any mistakes the user may have made entering the number into the textbox.

' 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

Convert the strings to numbers then use an if / elseif. The order of checks is important

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

This demonstrates why string comparisons are not a good idea in this case

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM