如何中断 If Else 语句 vb.net

How to break and If Else statement vb.net

我正在尝试从组合框中获取用户 select 设备并单击按钮。但是,当他们单击按钮时... MessageBox 显示但也继续单击按钮。如何阻止按钮点击继续,直到用户 select 的设备?

Private Sub EstablishConnection_Click(sender As Object, e As EventArgs) Handles EstablishConnection.Click

        Dim DeviceValidFalg As Boolean = True

        If DeviceDropDownList.Text = "USB" Then
            DeviceName = "USB Adapter"
        ElseIf DeviceDropDownList.Text = "USB1" Then
            DeviceName = "USB HDMI"
        ElseIf DeviceDropDownList.Text = "USB2" Then
            DeviceName = "HGCV"
        ElseIf DeviceDropDownList.Text = String.Empty Then
            DeviceValidFalg = False
            MessageBox.Show("Select a valid device")
        End If


重构逻辑以满足业务需求 - 必须以不同方式处理错误的输入。

例如(一种方法)您可以将两条路径包装在一个 If-Then-Else 块中:

Private Sub EstablishConnection_Click(sender As Object, e As EventArgs) Handles EstablishConnection.Click

        Dim DeviceValidFalg As Boolean = True

        If DeviceDropDownList.Text <> String.Empty Then
            Select Case DeviceDropDownList.Text
                Case "USB"
                    DeviceName = "USB Adapter"
                Case "USB1"
                    DeviceName = "USB HDMI"
                Case "USB2"
                    DeviceName = "HGCV"
                Case Else
                    ' Some other code of your choosing here
            End Select
            ' The rest of your logic here
        Else
            DeviceValidFalg = False
            MessageBox.Show("Select a valid device")
        End If

我更喜欢 Case 而不是 ElseIf 来进行简单检查(就像你在这里做的那样),因为它更干净、更容易阅读,因此更容易维护。

另一种方法可能是尽早 Exit Sub(正如@CoderCharmander 在评论中指出的那样):

Private Sub EstablishConnection_Click(sender As Object, e As EventArgs) Handles EstablishConnection.Click

        Dim DeviceValidFalg As Boolean = True

        If DeviceDropDownList.Text = String.Empty Then
            DeviceValidFalg = False
            MessageBox.Show("Select a valid device")
            Exit Sub
        End If

        Select Case DeviceDropDownList.Text
            Case "USB"
                DeviceName = "USB Adapter"
            Case "USB1"
                DeviceName = "USB HDMI"
            Case "USB2"
                DeviceName = "HGCV"
            Case Else
                ' Some other code of your choosing here
        End Select
        ' The rest of your logic here

最好的重构是确保他们在获得有效输入之前无法单击按钮(禁用它)!即,根据各种用户输入控件的值启用按钮。

附录(来自评论中的@JohnPete22):

If Not String.IsNullOrWhiteSpace(DeviceDropDownList.Text) 而不是 DeviceDropDownList.Text <> String.Empty 更好地使用 VB.Net String 构造并允许字符串不是 Trimmed 来自输入的情况.当然,在我的第二个例子中,为 = 删除 Not