Stop executing the rest of the code when condition is met within if statement

1.3k Views Asked by At

How can I jump to a textbox if the user left it empty. The if-else I used displays the message box but still continues the rest of the code.

Here's my code:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "" Then
        MsgBox("enter word to search for")
    End If
    WebBrowser1.Hide()
2

There are 2 best solutions below

1
On

You can do this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If TextBox1.Text = "" Then
    MsgBox("enter word to search for")
    TextBox1.Focus()
    Exit Sub
End If
WebBrowser1.Hide()
0
On

You need to put WebBrowser1.Hide() on the else statement Try this:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "" Then
        MsgBox("enter word to search for")
    Else
         WebBrowser1.Hide()
    End If

or you can use an Exit Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If TextBox1.Text = "" Then
        MsgBox("enter word to search for")
        Exit Sub
    End If
    WebBrowser1.Hide()