简体   繁体   English

如何验证我的文本框仅显示大于或等于0?

[英]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. 我有一个按钮将文本框的值增加1,而另一个按钮则相反。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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