Thursday, December 15, 2011

Allow NUMBERS, BACKSPACE and a DOT in a textbox

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress

'There are a couple scenerios this code is looking for. One is checking for the Decimal period "."
'and whether it exists in the textbox already. The other is seeing if the keypress was a Number and
'Control based key.


If e.KeyChar = "." Then


'If a value higher than -1 is returned, it means there IS a existing decimal point’


If TextBox1.Text.IndexOf(".") > -1 Then

'This says that I already dealt with the _KeyPress event so do not do anything else with this event.


e.Handled = True

End If

'Remember you want numbers to get through and the Control keys like “Backspace”

ElseIf Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False Then

'This says that I already dealt with the _KeyPress event so do not do anything else with this event.

e.Handled = True

End If
End Sub

No comments:

Post a Comment