I'm having trouble with validating my textbox.

My textbox should only accept decimal number, and should not accept negative number.

i tried this code for validating the input type, but i fail.

If Not Char.IsDigit(numWeight.Text) Then
            MsgBox("Incorrect input.")
        End If

And i don't know if this is the right code for validating for negative numbers.

If numWeight.Text.StartsWith("-") Then
            MsgBox("Invalid weight.")
            numWeight.Clear()
        End If

Please guys need help. Thank you, and God bless.

you can write code to accept numbers only and not other character..
try this :

Private Sub numWeight_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles numWeight.KeyPress
        Select Case Microsoft.VisualBasic.Asc(e.KeyChar)
            Case 48 To 57, 8
                'Let these key codes pass through
            Case Else
                e.Handled = True
        End Select
    End Sub

But it doesn't accepting decimal sign.

See if this helps.

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Select Case e.KeyChar
            Case "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, "0"c, CChar(vbBack) '// your #'s and Backspace.
                e.Handled = False '// allow.
            Case "."c '// Decimal dot.  allow only one.
                If Not TextBox1.Text.Contains(".") Then e.Handled = False Else e.Handled = True
            Case Else
                e.Handled = True '// block.
        End Select
    End Sub

this allows you to accept it :

Private Sub numWeight_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles numWeight.KeyPress
        Select Case Microsoft.VisualBasic.Asc(e.KeyChar)
            Case 46, 48 To 57, 8 '46 is . ascii key
                'Let these key codes pass through
            Case Else
                e.Handled = True
        End Select
    End Sub

@Codeorder : great code :)

Wow, thank you so much. it worked, thank you both of you. :/ our professor in vb didn't teach us well. so we're lack of knowledge in vb.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.