【问题标题】:How to use nested if-else in vb.net如何在 vb.net 中使用嵌套的 if-else
【发布时间】:2017-12-16 11:48:56
【问题描述】:

我正在做计算器,如果用户不向 num1 和 num2 输入值,我会编写代码,它会向屏幕显示消息,我使用 if-else 来完成。它适用于 num1 和运算符,但不适用于 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 

【问题讨论】:

    标签: vb.net if-statement nested


    【解决方案1】:

    你的代码应该是这样的:

    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

    【讨论】:

    • 你说得对,但他是初学者,所以我避免添加代码。
    • 你的意思是? Private Sub textbox1_leave(sender As System.Object, e As System.EventArgs) 处理 TextBox1.Leave If TextBox1.Text = "" Then TextBox1.Focus() Label1.ForeColor = Color.Red Return Else Label1.ForeColor = SystemColors.ControlText End如果结束子
    • 我要为 textbox2_leave 和 combobox 做私有子吗?
    猜你喜欢
    • 1970-01-01
    • 2020-10-15
    • 2021-12-18
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多