Saturn
Saturn

Reputation: 18159

Only accept digits in textbox

Given a texbox, how can I completely ignore non-digit characters? So if I press "A" or "Z", those characters would never appear in the textbox. I'd like to run a bit of code if the user tries to input digits and if he tries to input non-digits too..

Upvotes: 0

Views: 9067

Answers (4)

Johnbosco Adam
Johnbosco Adam

Reputation: 91

The code below works:

Private Sub txtSalary_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtSalary.KeyPress
    If (e.KeyChar < Chr(48) Or e.KeyChar > Chr(57)) And e.KeyChar <> Chr(8) Then
        e.Handled = True
    End If
End Sub

Upvotes: 0

Bala R
Bala R

Reputation: 109027

Try this

Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBox1.KeyPress
    If Char.IsDigit(e.KeyChar) Then
        e.Handled = False
    Else
        e.Handled = True
    End If

End Sub

if e.Handled is set to true for non-digits no input will go to the text box; otherwise the event messages flow as they normally would.

EDIT:

To handle BackSpace and Delete is a little more work but you can try this

Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textBox1.KeyPress
    If Char.IsDigit(e.KeyChar) OrElse e.KeyChar = CChar(Keys.Delete) OrElse e.KeyChar = CChar(Keys.Back) Then
        e.Handled = False
    Else
        e.Handled = True
    End If

End Sub

Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
    If keyData = Keys.Delete OrElse keyData = Keys.Back Then
        OnKeyPress(New KeyPressEventArgs(CChar(keyData))
    End If

    Return MyBase.ProcessCmdKey(msg, keyData)
End Function

KeyPress event does not get fired for Delete and Backspace keys and hence the override of ProcessCmdKey to manually call the form's OnKeyPress()

Upvotes: 5

Dan
Dan

Reputation: 1509

One method would be to use a "MaskedTextBox" control and set its handy "Mask" property

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32596

You could run a test in the OnKeyPress event (or whatever the event name is in winforms)

Upvotes: 0

Related Questions