Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to limit the keypress by just entering decimal numbers

Status
Not open for further replies.

programlover83

Programmer
Oct 11, 2003
1
US
How can I limit the keypress event for just handling the decimal numbers, to be precise how can I enter some amount with only 2 decimal places.

Here is the skeleton of what I am working on:

Private Sub KeyPressingNum(ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim KeyAscii As Integer
KeyAscii = Asc(e.KeyChar)
Select Case KeyAscii
Case Is < Keys.Space
'Ignore
Case Keys.D0 To Keys.D9
'Ignore
Case Else
MessageBox.Show(&quot;Please enter only numbers.&quot;, &quot;Error&quot;)
e.Handled = True
End Select
End Sub

Any help would be great.
Thanks
 
I'm using the following in a subclassed textbox control:

Sub OnKeyPress(ByVal e As KeyPressEventArgs)

MyBase.OnKeyPress(e)

Dim Keystroke As Integer = Asc(e.KeyChar)
' only 1 decimal point allowed
If Keystroke = 46 And (InStr(Me.Text, &quot;.&quot;)) Then
e.Handled = True
Exit Sub
'allow 'minus' only if specifically allowed and first character
ElseIf Keystroke = 45 And ((Len(Me.Text) > 0) Or Not m_AllowNegative) Then
e.Handled = True
Exit Sub
ElseIf (Keystroke < 48 Or Keystroke > 57) And _
(Keystroke <> 45 And Keystroke <> 46 And Keystroke <> 8) Then
e.Handled = True
Exit Sub
End If

End Sub

This will allow only numeric entry, and handles decimal places and negative numbers. You'll need to add code to look at the decimal place; look at the InStrRev function, which gives the location of a string within another from the end.
As a suggestion, rather than putting up a message saying to only input numeric values, don't allow non-numerics to be entered at all (I personally hate MessageBoxes popping up).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top