If ElseIf Else Statements in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes how to write a code that selectively perform different actions depending on the circumstances.

When you want to choose between executing two different blocks of code depending on the result of a Boolean expression, you usually use an if statement.

An if statement may be composed of complex expressions as well and can contain else/elseif statements to perform more complex testing.

Whenever you need to choose between executing two different blocks of code depending on the result of a Boolean expression, you use an if statement.
The syntax of an if statement is as follows:

If booleanExpression = True Then
    DoSomething()
Else 
    DoSomethingElse()
End If
' NOTE: an if statement is optionally followed by an else clause
                

Meaning, if booleanExpression evaluates to true, DoSomething() runs; otherwise, DoSomethingElse() runs. The Else keyword and the subsequent code are as previously mentioned optional. If there is no else clause and the booleanExpression is false, execution continues with whatever code follows the if statement.

Sometimes when you need to evaluate an identical expression with a different value you write a cascading if statement using ElseIf clause

Dim IsUsernameValid As Boolean
If Username.Text = "user" Then
    IsUsernameValid = False
ElseIf Username.Text = "admin"
    IsUsernameValid = True
Else 
    IsUsernameValid = False
End If
' NOTE: an if statement is optionally followed by an ElseIf clause as well
                

Previous Lesson | Next Lesson


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.