Click here to Skip to main content
15,906,645 members
Please Sign up or sign in to vote.
2.25/5 (4 votes)
See more:
i make a textbox i want to enter only integer data if any one want to type string
data type then generate a message "plese enter integervalue" i am using vb.net and making window based application
Posted

Try this in TextBox KeyPress Event.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If (Microsoft.VisualBasic.Asc(e.KeyChar) < 48) _
               Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) Then
            e.Handled = True
        End If
        If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
            e.Handled = False
        End If
    End Sub
 
Share this answer
 
This is very basic thing. You can do this using TextBox_KeyPress event, where you can add this code

C#
If Not (e.KeyChar.IsDigit(e.KeyChar)) And _
e.KeyChar <> ChrW(Keys.Back) Then
e.Handles = True
End If
 
Share this answer
 
v2
You can try given code which enable to user to enter only Digit.
 Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        
If Not (Char.IsDigit(e.KeyChar)) Then e.Handled = True
   
 End Sub
 
Share this answer
 
Another method is the isnumeric function, further reading MSDN: IsNumeric[^]

VB
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
       If Not IsNumeric(e.KeyChar) Then
           messagebox.show("Please enter a numeric value")
       End If
   End Sub


Updated thanks to Manfred seeing a problem in the code

VB
 Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If Char.IsNumber(e.KeyChar) OrElse Char.Equals(e.KeyChar, CType("-", Char)) Then
        'this test to see if "-" appears after the second character i.e. -100- this wont happen
        If TextBox1.Text.Length > 1 And Char.Equals(e.KeyChar, CType("-", Char)) Then
            e.Handled = True
        Else
            e.Handled = False
        End If
    Else
        e.Handled = True
    End If
End Sub
 
Share this answer
 
v3
Comments
Manfred Rudolf Bihy 8-Aug-11 10:07am    
What about negative integers?
Simon_Whale 8-Aug-11 10:32am    
Oh that gives a big bug :( fixed thanks Manfred and I can use that for a problem that I have in a project at the moment :)

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