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:
Statement –block a;
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:
- 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:
- 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:
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 outside if block")