0

我正在使用以下代码:

If IsNumeric(TextBox2.Text) Then
    not important code
Else
    MsgBox("O campo minutos só pode conter números!")
End If

基本上我需要检查文本框中插入的数据是否只是数字,当我插入字母或特殊字符(如 # 或 $到代码。

这是正常的吗?如果是这样,即使它有 + 或 - 有没有办法给出错误?当我使用 *、/ 或 = 时,它也会弹出错误。

4

5 回答 5

1

IsNumeric() 撒下了一张大网。它还将货币价值视为数字。好吧,他们当然是会计师。

如果您想让它更具限制性,请使用更具体到您喜欢的数字类型的转换方法。像 Double.TryParse()。

于 2013-07-24T15:04:55.540 回答
1

据我了解,您只想保留数字字符(没有“。”,“,”,...)使用Where()和VB的lamba表达式。这将选择然后计算不在数字字符串中的任何字符,然后检查计数是否等于零。

If IsNumeric(myString.Where(Function(c) Not "0123456789".Contains(c)).Count() = 0) Then
    not important code
Else
    MsgBox("O campo minutos só pode conter números!")
End If

更好,使用Any()而不是Where().Count()

If IsNumeric(Not myString.Any(Function(c) Not "0123456789".Contains(c))) Then
    not important code
Else
    MsgBox("O campo minutos só pode conter números!")
End If

这也可以用正则表达式来完成。

于 2013-07-24T15:00:16.407 回答
1

以防万一你想让它看起来更好尝试

If IsNumeric(TextBox2.Text) And TextBox2.Text.Contains("+") or Textbox2.Text.Contains("-")        
Then
    not important code
Else
MsgBox("O campo minutos só pode conter números!")
End If

PS:很高兴你想通了希望这会有所帮助

于 2013-07-25T17:49:24.367 回答
0

感谢您的所有帮助,我尝试了您的建议,但不知何故他们没有工作:S

设法解决了这样的问题:

For Each c As Char In TextBox1.Text
    If c = "+" Or c = "-" Then
        i = i + 1
    End If
Next
If IsNumeric(TextBox2.Text) And i = 0 Then
    not important code
Else
    MsgBox("O campo minutos só pode conter números!")
End If

再一次感谢你的帮助

于 2013-07-24T17:21:47.930 回答
0

也许使用文本控件的 KeyDown 事件会有所帮助?

Private Sub TextBox2_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyDown
    Select Case e.KeyValue
        Case Keys.NumPad0 To Keys.NumPad9
            ' code here for keys 0 through 9 from Keypad
        Case Keys.D0 To Keys.D9
            ' code here for keys 0 through 9 from top of keyborad

        Case Keys.Multiply, Keys.Divide, Keys.Add
            ' code here gor other characters like * / + etc.
        Case Else
            ' Code here for all other keys, supress key if needed
            e.SuppressKeyPress = True
    End Select
End Sub

http://www.asciitable.com/index/asciifull.gif

于 2013-07-24T17:31:15.757 回答