# The Nested If statement

• A nested If is a statement that is the target of another If or Else statements.
• When we use If, if..Then..ElseIf..Else, If..Then..Else statements inside the other If, ElseIf or Else statements that is known as nested If statements. When we use if statement inside the if then it is called as nested if statements.
• The syntax of the nested if statements are given below:
• If condition-1 Then
If condition-2 Then
Statement-block 1
Else
Statement-block 2
End If
Else
Statement-block 3
End If
Statement-block n

NOTE: A nested If statement contains various structures like If..Else statement inside If, If statement inside Else etc.

In the above syntax if condition-1 is true then condition-2 will be checked and if it is true then Statement-block 1 will be executed followed by Statement-block n and if it is false then Statement-block 2 will be executed followed by Statement-block n and if the condition-1 is false then Statement-block 3 will be executed followed by Statement-block n. You can understand this concept with the help of following diagram:

#### Working with Nested If statement

Here we are going to create a project in which we are using Nested If 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 Nestedifstatement, and click OK as shown in figure:

• 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:

• 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
Dim b As Integer = 3
If (a = 2) Then
MessageBox.Show("You are inside outer If block and value of a is:" & a.ToString, _"outerifstatement")
If (b = 3) Then
MessageBox.Show("You are inside nested If block and value of b is:" & b.ToString, _"nestedifstatement")
Else
MessageBox.Show("You are inside nested Else block and value of b is:" & b.ToString, _"nested Else statement")
End If
Else
MessageBox.Show("You are inside outer Else block and value of a is:" & a.ToString, _"outer Else statement")
End If
MessageBox.Show("You are outside nested If statement")
End Sub

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

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

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

• Now again press OK button present on the message box this will show a another message box as given below: