onemillionwords17 onemillionwords17 - 1 month ago 9
Vb.net Question

How to not allow textbox to have a negative value? (Visual Basic)

noob question here. I'm trying to write a program so that when someone left clicks on a label, the value in a text box goes up by 1. When they right click on it, the value goes down by 1. It all works, except I don't want the value to ever be able to become a negative number. I tried to stop it from happening, and it works when a positive value is already in the textbox. BUT if you right click the label before you left click it (before any value is in the textbox), it still becomes '-1' and then stops there. Here is the code I'm using: 

Private Sub Label5_MouseClick(sender As Object, e As MouseEventArgs) Handles Label5.MouseClick

If e.Button = MouseButtons.Left Then
SawWhetOwl.Text = (Val(SawWhetOwl.Text) + 1).ToString()
Label5.Text = SawWhetOwl.Text
ElseIf e.Button = MouseButtons.Right Then
If SawWhetOwl.Text = CInt(SawWhetOwl.Text < 0) Then
Exit Sub
Else
SawWhetOwl.Text = (Val(SawWhetOwl.Text) - 1).ToString()
Label5.Text = SawWhetOwl.Text
End If
End If
End Sub


The problem, I think, is that the value in the text box is starting off as empty, with no value assigned to it. Therefore when I right click it before a value is given to it, it can't calculate whether or not it's less than 0 and it just gives me -1, I think. I'm pretty confused, sorry if this question is confusing. Am I missing something obvious?

Answer

You may need to check text is not empty for decreasing the count.

Private Sub Label5_MouseClick(sender As Object, e As MouseEventArgs) Handles Label5.MouseClick

    If e.Button = MouseButtons.Left Then
        SawWhetOwl.Text = (Val(SawWhetOwl.Text) + 1).ToString()
        Label5.Text = SawWhetOwl.Text
    ElseIf e.Button = MouseButtons.Right Then
        If  String.IsNullOrEmpty(SawWhetOwl.Text) OrElse CInt(SawWhetOwl.Text) <= 0 Then
            Exit Sub
        Else
            SawWhetOwl.Text = (Val(SawWhetOwl.Text) - 1).ToString()
            Label5.Text = SawWhetOwl.Text
        End If
    End If
End Sub