So far i have a code that only allows you to enter numbers but how do i limit the value from 0 - 9999.

Also how would i be able to display a message label if the user is doing something illegal. Right now i have the messagebox setup but i need to display a error label.

    Private Sub empIDbox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles empIDbox.KeyPress
        'Makes sure only numeric values are entered
        If (e.KeyChar < Chr(48) Or e.KeyChar > Chr(57)) And e.KeyChar <> Chr(8) Then
            e.Handled = True
            addBtn.Enabled = False
            MessageBox.Show("Please enter only numeric values from 0 - 9999")
            addBtn.Enabled = True
        End If
    End Sub

THanks for your help

Recommended Answers

All 6 Replies

select your TextBox and then goto properties window and set MaxLength to 4.
Or double click your form and write on load form

TextBox1.MaxLength = 4

Ok thank you so much

What if the number was between 0 - 1500 ... i know to set the length but how would i stop the user from going over 1500

Try this
If TextBox1.Text > 1500 Then
MsgBox(" number not in range ")
Exit Sub
End If

If TextBox1.Text > 1500 Then

Doesn't work because you can't directly compare strings and numbers. Also

If TextBox1.Text > "1500" Then

won't work because "2" > "1500". If you limit your textbox to entering numbers only then you can do

If CInt(TextBox1.Text) > 1500 Then

To restrict a textbox to digits only you add

Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    e.Handled = InStr("1234567890", e.KeyChar) = 0 And Asc(e.KeyChar) <> Keys.Back
End Sub

This allows only digits, backspace, delete and left/right cursor.

For something a little fancier try playing with the following. Each time a digit is pressed, it saves the current (before inserting the new digit) in the Tag property. This is used to undo the newest digit if the resulting value exceeds some threshhold.

    Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim txt As TextBox = sender
        txt.Tag = txt.Text
        e.Handled = InStr("1234567890", e.KeyChar) = 0 And Asc(e.KeyChar) <> Keys.Back
    End Sub    

    Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
        Dim txt As TextBox = sender
        If CInt(txt.Text) > 1500 Then
            txt.Text = txt.Tag
            MsgBox("too big")
        End If
    End Sub

ok thank you

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.