VB文本框接受非数字数据

时间:2016-10-13 14:15:53

标签: vb.net textbox numeric

我在VB中有一个文本框,设置为只接受数字数据,除两种特定情况外,它都有效。

如果用户提供非数字字符,文本框会自行清除,

但是,如果用户首先提供号码,则提供“ - ”或“+”

文本框将接受此作为有效输入。

当用户再输入一个任意类型的字符,即数字或字符

然后文本框'实现'并且将自我清除。

我想知道这是否是由于VB存储字符' - '和'+'的方式?

最好的解决方法是加入两个例外,即输入“ - ”或“+”然后自我清除?

或者是否有更优雅的解决方案?

谢谢。

代码:

Private Sub TextBox1_Change()

'Textval used as variable from user input
'Numval becomes textval providing the user input is numerical

Dim textval As String
Dim numval As String

  textval = TextBox1.Text
  If IsNumeric(textval) Then
    numval = textval
  Else
    TextBox1.Text = CStr(numval)
  End If
End Sub

3 个答案:

答案 0 :(得分:0)

代码vb.net:

If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then
' your code here 
   e.Handled = True

结束如果

你可以替换文字: 代码:

Text = Text.Replace("string", "replace_by_this_string")

答案 1 :(得分:0)

如果程序要求用户只在文本框中键入数字数据,则应在用户按下某个键时强制执行该限制

使用文本框的KeyDown事件:

'Omitting the parameters and Handles keyword
Private Sub textbox_KeyDown()
    'Set the keys you would want to allow in this array
    Dim allowedkeys As Keys() = {Keys.D1, Keys.D2, Keys.D3, Keys.D4, Keys.D5, Keys.D6, Keys.D7, Keys.D8, Keys.D9, Keys.D0, Keys.Back}

    For i = 0 To allowedkeys.Length - 1 'Iterate through the allowed keys array
        If e.KeyCode = allowedkeys(i) Then 'If the key pressed is present in the array...
            Exit Sub 'The check returned a success. Exit and accept the key
        End If
    Next
    e.SuppressKeyPress = True 'Supress all keys that failed the check
End Sub

不要忘记添加您需要的更多密钥! Space键,小键盘键,点(点)键?

这样您就可以移除Changed事件中的支票,直接转到numval = textval

或者对于那些懒惰的程序员,numval = TextBox1.Textnumval = Val(TextBox1.Text)也可以使用

答案 2 :(得分:-2)

您需要尝试解析输入以仅允许您想要的内容。如果解析成功,则单独留下该字段,否则将从控件中删除该文本...

Private Sub TextBox1_Change()
   Dim intVal As Integer = 0
   If Not Integer.TryParse(TextBox1.Text, intVal) Then
      TextBox1.Text = String.Empty
   End If
End Sub

这只允许Integer类型,非字母字符......

相关问题