问题
机房重构的过程中涉及到数据类的文本框,比如说基本数据设定,充值金额等,是不允许输入除了数字以外的类型的,因为一旦输入肯定会因为数据类型问题报错。
方法
在模块中写一个公共方法
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 = 1)
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 <= 1 Then
blnHandled = True
Else
If Not (InStr(TargetTextBox.Text,".") = 1 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,".") > 1 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 txtLeastCash_KeyPress(sender As Object,e As KeyPressEventArgs) Handles txtLeastCash.KeyPress
CheckTextBox.CheckKeyPress(sender,e,False,1)
End Sub
Private Sub txtPreTime_KeyPress(sender As Object,e As KeyPressEventArgs) Handles txtPreTime.KeyPress
CheckTextBox.CheckKeyPress(sender,1)
End Sub
Private Sub txtStaUnit_KeyPress(sender As Object,e As KeyPressEventArgs) Handles txtStaUnit.KeyPress
CheckTextBox.CheckKeyPress(sender,1)
End Sub