如何控制TextBox控件只能输入数值型字符串

  1. Public Sub CheckKeyPress(ByVal TargetTextBox As TextBox, ByVal e As System.Windows.Forms.KeyPressEventArgs, Optional ByVal Minus As Boolean = FalseOptional ByVal DecimalCount As Integer = 0)
  2.         Dim blnHandled As Boolean
  3.         blnHandled = False
  4.         Select Case Asc(e.KeyChar)
  5.             Case Asc("-")                   '   负号:只能在最前头
  6.                 If Not (TargetTextBox.SelectionStart = 0 And Minus = TrueThen blnHandled = True
  7.             Case Asc(".")                   '   小数点:小数位数大于0;在字符串中没有“.”,且加了“.”后小数位能满足要求
  8.                 If DecimalCount <= 0 Then
  9.                     blnHandled = True
  10.                 Else
  11.                     If Not (InStr(TargetTextBox.Text, ".") = 0 And (Len(TargetTextBox.Text) - TargetTextBox.SelectionStart <= DecimalCount)) Then blnHandled = True
  12.                 End If
  13.             Case 8, 13                      '   退格键,回车键
  14.             Case Asc("0"To Asc("9")       '   0-9
  15.                 If InStr(TargetTextBox.Text, ".") > 0 Then
  16.                     If TargetTextBox.SelectionStart > InStr(TargetTextBox.Text, "."Then
  17.                         '   当前字符位置在小数点后,则小数点后的字符数必须小于小数位
  18.                         If Len(TargetTextBox.Text) - InStr(TargetTextBox.Text, ".") >= DecimalCount Then blnHandled = True
  19.                     Else
  20.                         '   当前字符位置在小数点前,则小数点后的字符数必须不大于小数位
  21.                         If Len(TargetTextBox.Text) - InStr(TargetTextBox.Text, ".") >= DecimalCount Then blnHandled = True
  22.                     End If
  23.                 End If
  24.             Case Else
  25.                 blnHandled = True
  26.         End Select
  27.         e.Handled = blnHandled
  28.     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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值