Limit textbox to numeric keys

S

ScareCrow

How do I go about limiting a textbox to accepting numeric key input from the keyboard in vb.net?




--------------= Posted using GrabIt =----------------
------= Binary Usenet downloading made easy =---------
-= Get GrabIt for free from http://www.shemes.com/ =-
 
L

Larry Serflaten

Herfried K. Wagner said:


Would you really rather use an expensive error trap when you can include
the test yourself? Testing it with code does not induce the delay you get while
the error is being caught....

Dim Source As TextBox = DirectCast(sender, TextBox)
Dim Message As String
If Source.Text Like "*[!0-9.]*" Then ' Remove '.' if decimals are not allowed.
Message = "Text is not expected here." & vbCrLf & "Enter a numeric value."
End If
Me.ErrorProvider1.SetError(Source, Message)

???
LFS
 
C

Cor Ligthert

Scare,

I made a sample after a long discussion in this newsgroup, the best of two
methods in my opinion.

http://groups-beta.google.com/group/microsoft.public.dotnet.languages.vb/msg/d0aa417bf7a25528

(It limits as well the lenght, however accepts as well decimal points and
exponents)
When you want only true numeric characters, than you get more a sample as
Herfried and Larry's.

Another advantage of this one is that it test during typing and not wait
until the end. I have somewhere one which does it during typing as well,
there are given a lot for that in this newsgroup, however that is in my
opinion easy to make as well from my sample combining with the code from
Larry.

I hope this helps?

Cor
 
H

Herfried K. Wagner [MVP]

Larry,

Larry Serflaten said:
Would you really rather use an expensive error trap when you can include
the test yourself? Testing it with code does not induce the delay you
get while
the error is being caught....

Dim Source As TextBox = DirectCast(sender, TextBox)
Dim Message As String
If Source.Text Like "*[!0-9.]*" Then ' Remove '.' if decimals are
not allowed.
Message = "Text is not expected here." & vbCrLf & "Enter a
numeric value."
End If
Me.ErrorProvider1.SetError(Source, Message)

That would work too and is a more evolved soltion :).
 
G

Guest

Try this:

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If (IsNumeric(e.KeyChar) = False) Then e.Handled = True
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top