如何在vb.net中使用嵌套的if-else

时间:2017-12-16 11:48:56

标签: vb.net if-statement nested

我正在做计算器,如果用户没有输入num1和num2的值,我会编写代码,它会给屏幕发消息,我用if-else做了。它适用于num1和operator,但不适用于num2。我该如何解决?

If TextBox1.Text = "" Or TextBox2.Text = "" Then
            If TextBox1.Text = "" Then
                MsgBox("Please enter data to number 1 ")
                TextBox1.Focus()
                Label1.ForeColor = Color.Red
            Else
                Label1.ForeColor = SystemColors.ControlText
            End If
        ElseIf TextBox1.Text = "" Or TextBox2.Text = "" Then
            If TextBox2.Text = "" Then
                MsgBox("Please enter data to number 2")
                TextBox2.Focus()
                Label2.ForeColor = Color.Red
            Else
                Label1.ForeColor = SystemColors.ControlText
            End If
        End If 

1 个答案:

答案 0 :(得分:0)

您的代码应该是:

If TextBox1.Text = "" Or TextBox2.Text = "" Then
    If TextBox1.Text = "" Then
        MsgBox("Please enter data to number 1 ")
        TextBox1.Focus()
        Label1.ForeColor = Color.Red
    End If
    ' Seperate the conditions because TextBox1 and TextBox2 can both be empty, so an ElseIf will not handle it
    If TextBox2.Text = "" Then
        MsgBox("Please enter data to number 2")
        TextBox2.Focus()
        Label2.ForeColor = Color.Red
    End If
Else ' Neither of them (so TextBox1 and TextBox2 won't be empty)
    Label1.ForeColor = SystemColors.ControlText
End If

当用户将TextBox1留空或TextBox2为空时,这将弹出一条消息,如果他没有留下任何两个为空,Else将启动。

有关VB.NET中条件的更多信息,请查看此处:https://www.dotnetperls.com/if-vbnet