[FONT="Courier New"]
Select Case Asc(e.KeyChar)
Case 48 To 57 'the number keys
Case 46 'the decimal key
If txtNumberKeyPad.Text.Contains(".") Then
e.Handled = True
End If
Case Keys.Back
Case Else
e.Handled = True 'this blocks all other key inputs
End Select[/FONT]
[FONT="Courier New"]Select Case Asc(e.KeyChar)
Case 48 To 57 'the number keys
Case 46 'the decimal key
If Not txtNumberKeyPad.Text.Contains(".") Then
If txtNumberKeyPad.Text.Length = 0 Then
e.Handled = True
txtNumberKeyPad.Text = "0."
txtNumberKeyPad.SelectionStart = txtNumberKeyPad.Text.Length
End If
Else
e.Handled = True
End If
Case Keys.Back
Case Else
e.Handled = True 'this blocks all other key inputs[/FONT]
End Select
And if you want to add a zero if it is the first key then use:
VB.NET:[FONT="Courier New"]Select Case Asc(e.KeyChar) Case 48 To 57 'the number keys Case 46 'the decimal key If Not txtNumberKeyPad.Text.Contains(".") Then If txtNumberKeyPad.Text.Length = 0 Then e.Handled = True txtNumberKeyPad.Text = "0." txtNumberKeyPad.SelectionStart = txtNumberKeyPad.Text.Length End If Else e.Handled = True End If Case Keys.Back Case Else e.Handled = True 'this blocks all other key inputs[/FONT] End Select
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Not Char.IsDigit(e.KeyChar) Then e.Handled = True 'allow only numerals
If e.KeyChar = Chr(8) Then e.Handled = False 'allow Backspace
If e.KeyChar = "-" And TextBox1.SelectionStart = 0 Then e.Handled = False 'allow negative numbers
If e.KeyChar = "." And TextBox1.Text.IndexOf(".") = -1 Then e.Handled = False 'allow only one decimal point
End Sub