VB.NET If statement

  • If statement is a most powerful decision making statement.
  • It allows the user to execute different path of logic on the basis of a given condition.
  • If the condition is true the block of statements present in the body of If statement gets executed and if condition is false then other set of statement after if structure gets executed.
  • Here is the syntax of if statement given below:
If condition Then
Statement –block a;
End if
Statement-block b;

If Condition is true then “Statement-block a” will be executed followed by “Statement-block b” and if condition is false then “Statement-block a will be skipped and execution will start from “Statement block-b”. You can understand this concept through the following diagram:


Working with simple If statement

Here we are going to create a project in which we are using an 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 ifstatement, and click OK as shown in figure:
  • if-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-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")
    End If
    MessageBox.Show("You are outside if block")
    End Sub

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

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

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