最好做一个用户控件,以便以后重复使用,
从TextBox继承
在KeyPress事件中写以下代码:
Dim KeyAscii As Integer
KeyAscii = Asc(e.KeyChar)
Select Case KeyAscii
Case 48 To 57, 8, 13 ' these are the digits 0-9, backspace,
' and carriage return
' we're OK on these, don't do anything
Case 45 ' minus sign
' if we already have one, throw it away
If InStr(Me.Text, "-") <> 0 Then
KeyAscii = 0
Exit Sub
End If
' if the insertion point is not sitting at zero
' (which is beginning of field), throw away the minus
' sign (because it's not valid except in first position)
If Me.SelectionStart <> 0 Then
KeyAscii = 0
End If
Case 46 ' this is a period (decimal point)
' if we already have a period, throw it away
If InStr(Me.Text, ".") <> 0 Then
KeyAscii = 0
End If
Case Else
' provide no handling for the other keys
KeyAscii = 0
End Select
' If we want to throw the keystroke away, then set the event
' as already handled. Otherwise, let the keystroke be handled normally.
If KeyAscii = 0 Then
e.Handled = True
Else
e.Handled = False
End If
不用这么麻烦,正则表达式就ok了
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
If Regex.IsMatch(TextBox3.Text, "^[\d|+|-]\d+[.]\d$") Then
MsgBox("OK!!")
Else
TextBox3.Text = ""
End If
End Sub
最简单的方法:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Not (IsNumeric(e.KeyChar) Or e.KeyChar = Microsoft.VisualBasic.ChrW(8) Or e.KeyChar = Microsoft.VisualBasic.ChrW(46)) Then
e.Handled = True
End If
End Sub