如果/否则语句VB.Net

If/else statement VB.Net

1
2
3
If txtNum1.Text <= 0 Or txtNum2.Text <= 0 Then
    lblResult.Text ="Result Error: Enter in a number graeter than zero"
End If

我是编程新手。我正在尝试创建一个if / else语句,以便如果任一文本框中的数字小于或等于0,它将显示一条错误消息,并且不会崩溃。


使用从字符串到数字的正确转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Dim res1 As Integer
Dim res2 as Integer

if Not Int.TryParse(txtNum1.Text, res1) then
   lblResult.Text ="Enter a valid first number"
   return
End If
if Not Int.TryParse(txtNum2.Text, res2) then
   lblResult.Text ="Enter a valid second number"
   return
End If

If res1 <= 0 OrElse res2 <= 0 Then
  lblResult.Text ="Result Error: Enter numbers greater than zero"
End If

您需要将用户输入转换为数字值。文本框的Text属性是字符串而不是数字。而且,如果要进行转换,则应该准备接收错误的输入(例如非数字值)。

最好的方法是使用Int.TryParse,它尝试将用户键入的值转换为数字,如果失败,则返回false。如果成功,将在第二个参数中找到转换后的数字。

还请注意,您应该使用OrElse而不是Or,因为前者使用短路评估

我想警告您有关错误消息似乎显而易见的另一个陷阱。 VB编译器试图帮助您将两个字符串转换为数字。从我的angular来看,这是非常糟糕的。您应该负责处理这种转换,从而禁用编译器的自动转换。转到项目的属性,页面Compile并设置the Option Strict to ON。这样,编译器将停止此自动转换,并在textBox1.Text <= 0

中将错误信号通知


您必须将.Text属性中的数字解析为整数。

所以您的If语句类似于

1
If Int32.Parse(txtNum1.Text) <= 0 ....

如果计划在代码中多次重用该值,则可以将其提取为变量。

此外,正如注释中指出的那样,您应该使用Int32.TryParse(value, number)检查无效数字,可以这样做。因此,如果TryParse(..)方法返回false,则可以处理这种情况。

要确切了解此方法的工作原理,可以阅读此内容

但是为了快速起见,value是要解析的字符串,而number是从字符串中解析出的整数值。该方法本身返回boolean(如果已成功解析,则为true,否则为false)


您的比较无法正常工作,您没有使用相同的类型(字符串与整数)
我宁愿使用integer.tryParse

因此代码变成类似:

1
2
3
4
5
6
7
8
9
dim n1 as integer
dim n2 as integer
if integer.tryparse(txtNum1.Text,n1) and integer.tryparse(txtnum2.text,n2) then
    If n1 <= 0 Or n2 <= 0 Then
        lblResult.Text ="Result Error: Enter in a number graeter than zero"
    End If
else
    lblResult.Text ="please input numbers"
end if

像这样的东西会更好,

您检查它是否为整数,然后检查它是否为零或不足

1
2
3
4
5
    Dim value1, value2 As Integer

    If not Integer.TryParse(txtNum1.text, value1) orelse value1 <= 0 OrElse not Integer.TryParse(txtNum2.text, value2) orelse value2 <= 0 Then
        lblResult.Text ="Result Error: Enter in a number graeter than zero"
    End If