VS2012上的IsNumeric(windows窗体)



我正在使用以下代码:

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

基本上,我需要检查插入文本框中的数据是否只有数字,当我插入字母或#或$等特殊字符时,它运行良好,并弹出错误,但如果我输入+6,它会进入代码。

这正常吗?如果是的话,有没有一种方法可以给出错误,即使它有+或-?当我使用*,/或=时,它也会弹出错误。

IsNumeric()抛出了一个相当大的网。它还认为货币价值是数字。嗯,他们当然是会计。

如果你想让它更具限制性,那么就使用一种更适合你喜欢的数字类型的转换方法。类似Double.TryParse().

据我所知,您只想保留数字字符(no".",",",…)使用CCD_ 1和VB的lambda表达式。这将选择并计数不在数字字符串中的任何字符,然后检查计数是否等于零。

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

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

如果你想让它看起来更好,试试

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:很高兴你发现了这一点,希望这能帮助

谢谢你的帮助,我试过你的建议,但不知怎么的,它们不起作用: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

再次感谢的帮助

也许使用文本控件的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

最新更新