Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how to restrict textbox entry in vb.net so that it accepts only numerical key and backspace to correct any error.

I am using this code:

VB
Private Sub TextBox3_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox3.KeyPress
        Dim allowedChars As String = "0123456789"

        If allowedChars.IndexOf(e.KeyChar) = -1 Then
            ' Invalid Character
            e.Handled = True
        End If

    End Sub


but its not including the backspace coding.
I need to allow backspace also. So please help.

Thanks!
Posted
Updated 9-Sep-10 1:51am
v3

Please check the following modified code:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim allowedChars As String = "0123456789"
        If e.KeyChar <> ControlChars.Back Then
            If allowedChars.IndexOf(e.KeyChar) = -1 Then
                'Invalid Character
                e.Handled = True
            End If
        End If
    End Sub
 
Share this answer
 
Add this If Asc(e.KeyChar) = Asc(Keys.Back) Then Exit Sub before If allowedChars.IndexOf(e.KeyChar) = -1 Then.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900