您的位置:首页 > 编程语言 > VB

vb.net控制TextBox控件只能输入数值型字符串

2010-01-06 13:04 555 查看
Module CheckTextbox
'以下代码控制TextBox控件只能输入数值型字符串,具体内容如下:
Public Sub CheckKeyPress(ByVal TargetTextBox As TextBox, ByVal e As System.Windows.Forms.KeyPressEventArgs, Optional ByVal Minus As Boolean = False, Optional ByVal DecimalCount As Integer = 0)
Dim blnHandled As Boolean
blnHandled = False
Select Case Asc(e.KeyChar)
Case Asc("-")                   '   负号:只能在最前头
If Not (TargetTextBox.SelectionStart = 0 And Minus = True) Then blnHandled = True
Case Asc(".")                   '   小数点:小数位数大于0;在字符串中没有“.”,且加了“.”后小数位能满足要求
If DecimalCount <= 0 Then
blnHandled = True
Else
If Not (InStr(TargetTextBox.Text, ".") = 0 And (Len(TargetTextBox.Text) - TargetTextBox.SelectionStart <= DecimalCount)) Then blnHandled = True
End If
Case 8  '退格键,
Case 13 ' 回车键
SendKeys.Send("{TAB}") '转为tab键
Case Asc("0") To Asc("9")       '   0-9
If InStr(TargetTextBox.Text, ".") > 0 Then
If TargetTextBox.SelectionStart > InStr(TargetTextBox.Text, ".") - 1 Then
'   当前字符位置在小数点后,则小数点后的字符数必须小于小数位
If Len(TargetTextBox.Text) - InStr(TargetTextBox.Text, ".") + 1 > DecimalCount Then blnHandled = True

End If
End If
Case Else
blnHandled = True
End Select
e.Handled = blnHandled
End Sub
'调用如下:
'    Private Sub txtJE_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtJE.KeyPress
'        CheckKeyPress(sender, e, False, 0)
'    End Sub
End Module
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: