CathaysMafia CathaysMafia - 11 days ago 5
Vb.net Question

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

Answer

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)