I have created a function and I put mine in a Class module that holds my custom functions. The function is called from the KEYPRESS event of any textbox control where you want to limit to numeric input.
The only parameter you may wish to change is the last parameter which determines the number of digits to the right of the decimal place. This sample code limits the input to 2 decimal places.
Code for KEYPRESS event
Expand|Select|Wrap|Line Numbers
- Dim myTextBox As TextBox
- myTextBox = Me.ActiveControl
- If myMiscClass.myNumOnly(e.KeyChar, Me.ActiveControl.Text, myTextBox.SelectionStart, 2) = True Then
- e.Handled = True
- Else
- e.Handled = False
- End If
- If e.KeyChar = Chr(13) Then GetNextControl(Me.ActiveControl, True).Focus() 'Enter key moves to next control
Expand|Select|Wrap|Line Numbers
- '*****************************************************
- ' myNumOnly()
- ' Purpose: Limits textbox input to numeric only
- ' Inputs: strKeyPress, key pressed
- ' strText, current text in textbox
- ' intPosition, current cursor position in textbox
- ' intDecimal, number of decimal places required
- ' ' Returns: False/True - discard keystroke/valid key
- '*****************************************************
- Shared Function myNumOnly(ByVal strKeyPress As String, ByVal strText As String, ByVal intPosition As Integer, ByVal intDecimal As Integer) As Boolean
- Dim dot As Integer, ch As String
- If Not Char.IsDigit(strKeyPress) Then myNumOnly = True
- If strKeyPress = "-" And intPosition = 0 Then myNumOnly = False 'allow negative number
- If strKeyPress = "." And strText.IndexOf(".") = -1 Then myNumOnly = False 'allow single decimal point
- dot = strText.IndexOf(".")
- If dot > -1 Then 'limit to set decimal places
- ch = strText.Substring(dot + 1)
- If ch.Length > (intDecimal - 1) Then myNumOnly = True
- End If
- If strKeyPress = Chr(8) Then myNumOnly = False 'allow Backspace
- Return myNumOnly
- End Function
cheers,