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

来源:互联网 发布:网络社交英文怎么说 编辑:程序博客网 时间:2024/05/16 14:41

以下代码控制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, 13                      '  
退格键,回车键
            Case Asc("0") To Asc("9")       '   0-9
                If InStr(TargetTextBox.Text, ".") > 0 Then
                    If TargetTextBox.SelectionStart > InStr(TargetTextBox.Text, ".") Then
                        '  
当前字符位置在小数点后,则小数点后的字符数必须小于小数位
                        If Len(TargetTextBox.Text) - InStr(TargetTextBox.Text, ".") >= DecimalCount Then blnHandled = True
                    Else
                        '  
当前字符位置在小数点前,则小数点后的字符数必须不大于小数位
                        If Len(TargetTextBox.Text) - InStr(TargetTextBox.Text, ".") >= 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
        gclsPublic.CheckKeyPress(sender, e, False, 0)
    End Sub

原创粉丝点击