方法一:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim strlimit As String
strlimit = "0123456789."
Dim keychar As Char = e.KeyChar
If InStr(strlimit, keychar) <> 0 Or e.KeyChar = Microsoft.VisualBasic.ChrW(8) Then
If keychar = "." And InStr(TxtEnter.Text, keychar) <> 0 Then
e.Handled = True
Else
e.Handled = False
End If
Else
e.Handled = True
End If
End Sub
方法二:
IsNumeric(TextBox1.Text)
方法三:
Private Sub TextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
If (e.KeyValue > 47 And e.KeyValue < 58) Or (e.KeyValue > 95 And e.KeyValue < 106) Or (e.KeyValue = 8) Or (e.KeyValue = 45) Or (e.KeyValue = 46) Then
str = TextBox1.Text
Else
TextBox1.Text = str
TextBox1.Focus()
End If
End Sub
方法四:
文本框防止非法字符輸入:
只輸入整數(shù):
Private Sub Text1_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case Asc("0") To Asc("9"), vbKeyBack
'nop
Case Else
KeyAscii = 0
End Select
End Sub
只輸入小數(shù):
Private Sub Text1_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case Asc("0") To Asc("9"), vbKeyBack
'nop
case Asc(".")'允許一個小數(shù)點
If InStr(1, Text1.Text, ".") > 0 Then KeyAscii = 0
Case Else
KeyAscii = 0
End Select
End Sub