【问题标题】:Getting error from Isnumeric() VB.NET从 Isnumeric() VB.NET 获取错误
【发布时间】:2013-09-21 17:06:03
【问题描述】:

在输入框中输入字母时出现运行时错误

Dim amount As String
        amount = InputBox("Enter the amount of people you want to participtate", "System Message")
        If amount < 0 Or Not (IsNumeric(amount)) Then
            MsgBox("Please enter positive number of people", vbExclamation, "System Message")
        End If

【问题讨论】:

  • If amount &lt; 0 语句出错了..
  • 请将 Option Strict On 放在代码文件的顶部或在项目属性中打开它。

标签: vb.net isnumeric


【解决方案1】:

将字符串与数字进行比较是非常危险的,而且会在你的脸上炸开。你可以让它工作,但你必须仔细编码,确保你永远不会尝试比较无法转换为数字的字符串。这需要使用另一个运算符:

    If Not IsNumeric(amount) OrElse amount < 0 Then
        MsgBox("Please enter positive number of people", vbExclamation, "System Message")
    End If

注意更改的顺序和 OrElse(Or 的短路版本)的使用。如果左边已经是 True,它不会计算右边的表达式。

更以 .NET 为中心的方法是使用 Integer.TryParse() 将字符串转换为数字。

【讨论】:

    【解决方案2】:

    为了避免错误,你可以这样..

    If IsNumeric(amount) Then
      If value(amount) > 0 Then
        'codes here
      Else      
         MsgBox("Please enter positive number of people", vbExclamation, "System Message")
      End If
    Else
      MsgBox("Please enter a number of people", vbExclamation, "System Message")
    End If
    

    【讨论】:

      【解决方案3】:

      所以我正在研究验证一个文本框,首先我想确保它不是空的,并确保它是一个数字。我绝不是专家,但我会将我编写的代码用于验证用户输入。我把它放在一个函数中,因为我有很多用户必须输入的文本字段。

      Class MainWindow 
      Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
          tb2.Text = tbCheck(tb1)
      End Sub
      
      Private Function tbCheck(ByRef tb As TextBox) As Boolean
          tbCheck = tb.Text.Length > 0
          Try
              tbCheck = (tb.Text / 1) > 0
          Catch ex As Exception
              tbCheck = False
          End Try
          Return tbCheck
      End Function
      

      结束类

      这只是我编写的用于检查代码是否按我希望的那样工作的简单程序。 希望这可以帮助某人,或者至少告诉我我是否缺少某些东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多