Friday, July 4, 2008

Textbox to accept only numeric value

Private Sub txtTurnover_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtTurnover.KeyPress
e.Handled = NumbersOnly(e.KeyChar, CType(sender, TextBox))
End Sub
Private Function NumbersOnly(ByVal pstrChar As Char, ByVal oTextBox As TextBox) As Boolean

If (Convert.ToString(pstrChar) = "." And InStr(oTextBox.Text, ".")) Then Return True 'accept only one instance of the decimal point
If Convert.ToString(pstrChar) <> "." And pstrChar <> vbBack Then
Return IIf(IsNumeric(pstrChar), False, True) 'check if numeric is returned
End If
Return False 'for backspace
End Function

No comments: