Click here to Skip to main content
15,905,686 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to input number only in a text box? And also can remove a character if I press the backspace key or delete key? I tried some code in the internet but it didn't remove a character if I press the backspace or delete key.

can you give me some code...
Posted
Comments
Sergey Alexandrovich Kryukov 23-Jul-12 2:45am    
If could be one of the several different types named TextBox: in WPF, Silverlight, ASP.NET, Forms... Tag it, tell us exact type.
--SA

Try this:
VB
Private Sub NumberValidation(sender As Object, e As KeyPressEventArgs)
    If (e.KeyChar >= 48 AndAlso e.KeyChar <= 57) OrElse e.KeyChar = 8 Then
        e.Handled = False
    Else
        e.Handled = True
    End If
End Sub
 
Share this answer
 
Comments
AmitGajjar 23-Jul-12 1:09am    
correct. 5+
Prasad_Kulkarni 23-Jul-12 1:15am    
Thank you Amit!
ianshack 23-Jul-12 3:53am    
sir, i get an error the code you gave.
Prasad_Kulkarni 23-Jul-12 3:55am    
What's that?
ianshack 23-Jul-12 3:56am    
Operator '>=' is not defined for types 'Char' and 'Integer'.
I got this message sir.
You should write you own custom textbox class, as in the link here:
http://www.daniweb.com/software-development/vbnet/code/353389/numberbox-textbox-that-takes-only-number-input[^]
This allows handling the keypress event and filtering out any character that is unwanted. For the delete and backspace key: They are normally working in textboxes without any added code.
 
Share this answer
 
VB
If Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Or Asc(e.KeyChar) = 8 Then
            e.Handled = False
        Else
            e.Handled = True
        End If



I tried this code and it works.

thanks to all.
 
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