this blog contains information for .net and sql stuffs. You can find various tips and tricks to overcome problem you may be facing in ...

Monday, November 17, 2008

How to allow only Numeric value in textbox?

this code snippest allow you to enter only numeric value to text box...

Private Function TrapKey(ByVal KCode As String) As Boolean
   If (KCode >= 48 And KCode <= 57) Or KCode = 8 Then
       TrapKey = False
   Else
       TrapKey = True
    End If
End Function

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        e.Handled = TrapKey(Asc(e.KeyChar))
End Sub

Alternate you can write common function like

 Public Sub NumbericText(ByVal sender As System.Object, ByVal e As KeyPressEventArgs)
        Dim ch As Integer = Asc(e.KeyChar)

        If (ch >= 48 AndAlso ch <= 57) Or ch = 8 Then
            e.Handled = False
        Else
            e.Handled = True
        End If
    End Sub

then add eventhandler for text box,

suppose ,in textbox txtId you just want to allow numeric value then you can do 

 AddHandler txtId.KeyPress, AddressOf  NumbericText

No comments: