The If..Then..Else statement

  • In this type of statement, there are two blocks are present: if and else. If block will always be executed when the given condition is true; if condition is false then else block will be executed. if-else statement take care of true as well as false condition.
  • if-else statement provides one alternative choice to the user. If condition is true then statements of if block will be executed and if condition is false then statements present inside the else block will be executed.
  • The general structure of an If..Then..Else statement is as follows:
  • If condition Then
    Statement-block 1;
    End If
    Statement-block n;

In the above syntax if condition is true then “Statement-block 1” will be executed followed by “Statement-block n” and if condition is false then “Statement-block 2” will be executed followed by “Statement-block n”. You can easily understand the concept by following diagram:


Working with If..Then..Else statement

Here we are going to create a project in which we are using a if..Then..Else statement:

  • Create a new project in Visual Studio 2010 by selecting File ➪ New Project from the menu bar. In the New Project dialog, select Windows Forms Application from the right-hand pane, enter the project name as ifThenElse , and click OK as shown in figure:
  • if-else-statement

  • Now drag and drop a Button control from the toolbox to the form and change its text property to “ShowOutput” as given below in the diagram:
  • if-else-statement

  • Double-click the button “ShowOutput” to open the Button1.Click event handler. Add the following given code to it:
  • Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim a As Integer = 2
    If (a > 2) Then
    MessageBox.Show("You are inside If block and value of a is:" & a.ToString, _"Ifstatement")
    MessageBox.Show("You are inside Else block and value of a is:" & a.ToString, _"Elsestatement")
    End If
    MessageBox.Show("You are outsideof If..Then..Else block")
    End Sub

  • Now execute the project by pressing F5 key it will open a form as follows:
  • if-else-statement

  • Now click on the button “ShowOutput” present on the form this will show you a message box as follows:
  • if-else-statement

  • Now press OK button present on the message box this will show a another message box as given below:
  • if-else-statement