【问题标题】:How do you check if an input is a negative number in VBVB中如何判断输入是否为负数
【发布时间】:2014-11-07 15:55:11
【问题描述】:

我正在尝试进行一些验证,检查文本框中的值是否为整数,然后检查该值是否为负。它正确检查该值是否为整数,但我无法检查该值是否为负。

注意:输入的值是参加的比赛次数,因此 comps = 比赛等...

Dim comps As Integer
    Dim value As Double
    If Integer.TryParse(txtCompsEntered.Text, integer) Then
        value = txtCompsEntered.Text
        If value < 0 Then
            lblcompsatten.ForeColor = Color.Red
            txtCompsEntered.ForeColor = Color.Red
            lblcompsatten.Text = "No negative numbers"
        Else
            lblcompsatten.ForeColor = Color.Black
            txtCompsEntered.ForeColor = Color.Black
            lblcompsatten.Text = ""
        End If
        lblcompsatten.ForeColor = Color.Black
        txtCompsEntered.ForeColor = Color.Black
        lblcompsatten.Text = ""
    Else
        lblcompsatten.ForeColor = Color.Red
        txtCompsEntered.ForeColor = Color.Red
        lblcompsatten.Text = "Not a number"
    End If

我已经看过这个帖子,但它似乎没有用 how-to-check-for-negative-values-in-text-box-in-vb

【问题讨论】:

  • 如果 Jon Skeet 的回答不起作用,你几乎可以肯定做错了什么。您混合了 Integer 和 Double 类型,根本没有使用 TryParse。

标签: vb.net validation negative-number


【解决方案1】:

如果成功,Tryparse 会将输入转换为整数 - 您不需要同时使用 comps 和 value 变量。以下是其工作原理的示例:

Dim comps As Integer
Dim input As String = "im not an integer"
Dim input2 As String = "2"

'tryparse fails, doesn't get into comps < 0 comparison
If Integer.TryParse(input, comps) Then
    If comps < 0 Then
        'do something
    End If
Else
   'I'm not an integer!
End If

'tryparse works, goes into comps < 0 comparison
If Integer.TryParse(input2, comps) Then
    If comps < 0 Then
        'do something
    End If
End If

【讨论】:

  • 谢谢。那是我没有第二个 integer.tryparse。
  • 你不需要同时拥有这两者......这只是一个例子,它会根据输入实际能够解析为整数而进入 comps
【解决方案2】:

您的代码存在一些问题,但主要问题是 Integer.TryParse 使用不正确。

不正确:

Dim value As Double
If Integer.TryParse(txtCompsEntered.Text, integer) Then
    value = txtCompsEntered.Text
        If value < 0 Then

正确:

Dim value As Integer
If Integer.TryParse(txtCompsEntered.Text, value) Then
    If value < 0 Then

需要注意的是,Integer.TryParse 将返回一个布尔值(如果该值可以转换为整数,则为 true,否则为 false)。他们会将转换后的值转储到您传递给它的第二个参数中。在您的情况下,您有“整数”,这是不正确的。您应该传入一个变量,然后使用该变量进行比较。

另外,请注意您的类型。当您似乎在使用整数时,您将“值”作为双精度数。

【讨论】:

    【解决方案3】:

    也许试试这个?

    If myinteger.toString.Contains("-") Then
        'it's negative
    Else
        'it isn't
    End If
    

    甚至更简单

    If myinteger < 0 Then
        'it's not negative
    Else
        'it is negative
    End if
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-27
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2022-06-28
      相关资源
      最近更新 更多