简体   繁体   中英

how do I validate my textbox to only display more than or equal to 0?

I have one button to increment the value of the text box by 1 and another button to do the opposite. I want to know how to validate it so the number doesn't go below zero.

Here is the code I have so far:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim i As Integer
    If Integer.TryParse(TextBox2.Text, i) Then
        i += 1
    Else
        i = 0
    End If
    TextBox2.Text = i.ToString()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim i As Integer
    If Integer.TryParse(TextBox2.Text, i) Then
        i -= 1
    Else
        i = 0
    End If
    TextBox2.Text = i.ToString()
End Sub

You have two easy options:

  • before you decrement the number, check if it is greater than zero
  • after you decrement the number, check if is less than zero and if so, set it to zero.

So..

If Integer.TryParse(TextBox2.Text, i) AndAlso (i > 0) Then
        i -= 1
    Else

or...

If Integer.TryParse(TextBox2.Text, i) Then
        i -= 1
        If i < 0 Then
            i = 0
        End If
    Else

You could also use

i = Math.Max(0, i - 1)

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