你如何检查输入是否为VB中的负数 [英] How do you check if an input is a negative number in VB

查看:44
本文介绍了你如何检查输入是否为VB中的负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to do some validation which checks if the value in a textbox is an integer then checks if the the value is negative. It correctly checks if the value is an integer but I can't get it to check if the value is negative.

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

Note: The value being entered is the number of competitions attended so comps = competition etc...

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

I have already looked at this thread but it didn't seem to work how-to-check-for-negative-values-in-text-box-in-vb

推荐答案

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

Tryparse will convert the input to an integer if it succeeds - you don't need both the comps and value variables. Here's an example of how it works:

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

这篇关于你如何检查输入是否为VB中的负数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆