加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

【机房重构】--VB.NET限制文本框类型为数字

发布时间:2020-12-17 07:32:36 所属栏目:百科 来源:网络整理
导读:问题 机房重构的过程中涉及到数据类的文本框,比如说基本数据设定,充值金额等,是不允许输入除了数字以外的类型的,因为一旦输入肯定会因为数据类型问题报错。 方法 在模块中写一个公共方法 Module CheckTextBox '以下代码控制TextBox控件只能输入数值型字

问题

机房重构的过程中涉及到数据类的文本框,比如说基本数据设定,充值金额等,是不允许输入除了数字以外的类型的,因为一旦输入肯定会因为数据类型问题报错。

方法

在模块中写一个公共方法

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

总结

因为经常要用到这个方法,所以抽象出来调用的时候感觉超级爽。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读