Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only accept digits for textbox

I found this code for making my textbox only accept numbers.

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim allowedChars As String = "0123456789"
    If allowedChars.IndexOf(e.KeyChar) = -1 Then
        ' Invalid Character
        e.Handled = True
    End If
End Sub

But... the user can't delete the numbers using the backspace button. How do I do then?

like image 601
Voldemort Avatar asked Jan 26 '11 04:01

Voldemort


3 Answers

 Private Sub txtValue_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles                 txtValue.KeyPress
        'Dim allowedChars As String = "0123456789"
        'If allowedChars.IndexOf(e.KeyChar) = -1 Then
        '    ' Invalid Character
        '    e.Handled = True
        'End If
        'If (e.KeyChar = Microsoft.VisualBasic.Chr(8)) Then
        '    e.Handled = True
        'End If
        If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
            e.Handled = True
        End If
    End Sub                                
like image 163
LV Ganesh Avatar answered Nov 07 '22 16:11

LV Ganesh


You also need to handle pasted text (there may not be a keypress). The best way to do this is with a MaskedTextBox.

like image 21
Joel Coehoorn Avatar answered Nov 07 '22 16:11

Joel Coehoorn


voldemort

i develop your first code to allow the user to delete too.

Here is the code :

Dim BACKSPACE As Boolean

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
    If e.KeyCode = Keys.Back Then
        BACKSPACE = True
    Else
        BACKSPACE = False
    End If
End Sub

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If BACKSPACE = False Then
        Dim allowedChars As String = "0123456789"
        If allowedChars.IndexOf(e.KeyChar) = -1 Then
            e.Handled = True
        End If
    End If
End Sub

I Hope My Code Was Useful To You :)

like image 30
Mousa Alfhaily Avatar answered Nov 07 '22 16:11

Mousa Alfhaily