Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

VB.

NET Program Flow Control Tutorials


 How to use IF ELSE END IF in VB.NET
 How to use FOR NEXT loop in vb.net
 How to use FOR EACH loop in VB.NET
 How to use vb.net While End While loop
 How to use Enum in vb.net
How to use IF ELSE in VB.NET

The conditional statement IF ELSE , is use for examining the


conditions that we provided, and making decision based on that
contition. The conditional statement examining the data using
comparison operators as well as logical operators.

If [your condition here]


Your code here
Else
Your code Here
End If

If the contition is TRUE then the control goes to between IF and Else
block , that is the program will execute the code between IF and
ELSE statements.

If the contition is FLASE then the control goes to between ELSE and
END IF block , that is the program will execute the code between
ELSE and END IF statements.

If you want o check more than one condition at the same time , you
can use ElseIf .
If [your condition here]
Your code here
ElseIf [your condition here]
Your code here
ElseIf [your condition here]
Your code here
Else
Your code Here
End If

Just take a real-time example - When we want to analyze a mark


lists we have to apply some conditions for grading students depends
on the marks.

Following are the garding rule of the mark list:

1) If the marks is greater than 80 then the student get higher first
class

2) If the marks less than 80 and greater than 60 then the student
get first class

3) If the marks less than 60 and greater than 40 then the student
get second class

4) The last condition is , if the marks less than 40 then the student
fail.

Now here implementing these conditions in a VB.NET program.

1. If totalMarks >= 80 Then


2. MsgBox("Got Higher First Class ")
3. ElseIf totalMarks >= 60 Then
4. MsgBox("Got First Class ")
5. ElseIf totalMarks >= 40 Then
6. MsgBox("Just pass only")
7. Else
8. MsgBox("Failed")
9. End If

Line 1 : Checking the total marks greaterthan or equal to 80

Line 2 : If total marks greater than 80 show message - "Got Higher


First Class "
Line 3 : Checking the total marks greaterthan or equal to 60

Line 4 : If total marks greater than 60 show message - "Got First


Class "

Line 5 : Checking the total marks greaterthan or equal to 40

Line 6 : If total marks greater than 40 show message - "Just pass


only"

Line 7 : If those three conditions failed program go to the next


coding block

Line 8 : If all fail shows message "Failed"

Line 9 : Ending the condition block

VB.NET Source Code


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim totalMarks As Integer
totalMarks = 59
If totalMarks >= 80 Then
MsgBox("Gor Higher First Class ")
ElseIf totalMarks >= 60 Then
MsgBox("Gor First Class ")
ElseIf totalMarks >= 40 Then
MsgBox("Just pass only")
Else
MsgBox("Failed")
End If
End Sub
End Class

In this example the total marks is 59 , when you execute this


program you will get in messagebox "Just Pass Only"

If you want to check a condition within condition you can use nested
if statements

If [your condition here]


If [your condition here]
Your code here
Else
Your code Here
End If
Else
Your code Here
End If

Also you can write IF ELSE Statements in a single line

If [your condition here] [Code] Else [code]

Download Source Code


Print Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim totalMarks As Integer
totalMarks = 39
If totalMarks >= 50 Then MsgBox("passed ") Else MsgBox("Failed ")
End Sub
End Class

When you execute this program you will get in messagebox "Failed "

How to use FOR NEXT loop in vb.net


Whenever you face a situation in programming to repeat a task for
several times (more than one times ) or you have to repeat a task
till you reach a condtition, in these situations you can use loop
statements to achieve your desired results. This kind of for loop is
useful for iterating over arrays and for other applications in which
you know in advance how many times you want the loop to iterate.

The FOR NEXT Loop , execute the loop body (the source code


within For ..Next code block) to a fixed number of times.

For var=[startValue] To [endValue] [Step]


[loopBody]
Next [var]
var : The counter for the loop to repeat the steps.

starValue : The starting value assign to counter variable .

endValue : When the counter variable reach end value the Loop will
stop .

loopBody : The source code between loop body

Lets take a simple real time example , If you want to show a


messagebox 5 times and each time you want to see how many
times the message box shows.

1. startVal=1
2. endVal = 5
3. For var = startVal To endVal
4. show message
5. Next var

Line 1: Loop starts value from 1

Line 2: Loop will end when it reach 5

Line 3: Assign the starting value to var and inform to stop when the
var reach endVal

Line 4: Execute the loop body

Line 5: Taking next step , if the counter not reach the endVal

VB.NET Source Code

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim var As Integer
Dim startVal As Integer
Dim endVal As Integer
startVal = 1
endVal = 5
For var = startVal To endVal
MsgBox("Message Box Shows " & var & " Times ")
Next var
End Sub
End Class
When you execute this program , It will show messagebox five time
and each time it shows the counter value.

If you want to Exit from FOR NEXT Loop even before completing


the loop Visual Basic.NET provides a keyword Exit to use within the
loop body.

For var=startValue To endValue [Step]


[loopBody]
Contition
[Exit For]
Next [var]
Next :  How to use FOR EACH loop in VB.NET

Download Source Code


Print Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim var As Integer
Dim startVal As Integer
Dim endVal As Integer
startVal = 1
endVal = 5
For var = startVal To endVal
MsgBox("Message Box Shows " var " Times ")
If var = 3 Then
Exit For
End If
Next var
End Sub
End Class

When you execute the above source code , the program shows the message box only
three times . 

How to use FOR EACH loop in VB.NET


Whenever you face a situation in programming to repeat a task for
several times (more than one times ) or you have to repeat a task
till you reach a condition, in these situations you can use loop
statements to achieve your desired results.
FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop
are the Commonly used loops in Visual Basic.NET 2005 ( VB.NET
2005) .

For Each Loop

FOR EACH Loop usually using when you are in a situation to execute
every single element or item in a group (like every single element in
an Array, or every single files in a folder or , every character in a
String ) , in these type of situation you can use For Each loop.

For Each [Item] In [Group]


[loopBody]
Next [Item]

Item : The Item in the group

Group : The group containing items

LoopBody : The code you want to execute within For Each Loop

Let's take a real time example , if you want to display the each
character in the website name "HTTP://NET-INFORMATIONS.COM" ,
it is convenient to use For Each Loop.

1. siteName = "HTTP://NET-INFORMATIONS.COM"
2. For Each singleChar In siteName
3. MsgBox(singleChar)
4. Next

Line 1: Assigning the site name in a variable

Line 2: This line is extracting the single item from the group

Line 3: Loop body

Line 4: Taking the next step

Next :  How to use vb.net While End While loop

Download Source Code


Print Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim siteName As String
Dim singleChar As Char
siteName = "HTTP://NET-INFORMATIONS.COM"
For Each singleChar In siteName
MsgBox(singleChar)
Next
End Sub
End Class

When you execute this program you will get each character of the string in
Messagebox. 

How to use vb.net While End While loop


Whenever you face a situation in programming to repeat a task for
several times (more than one times ) or you have to repeat a task
till you reach a condition, in these situations you can use loop
statements to achieve your desired results.

While ..End While


While .. End While Loop execute the code body (the source code
within While and End while statements ) until it meets the specified
condition. The expression is evaluated each time the loop is
encountered. If the evaluation result is true, the loop body
statements are executed.

While [condition]
[loop body]
End While

Condition : The condition set by the user

1. counter = 1
2. While (counter <= 10)
3. Message
4. counter = counter + 1
5. End While

Line 1: Counter start from 1

Line 2: While loop checking the counter if it is less than or equal to


10

Line 3: Each time the Loop execute the message and show

Line 4: Counter increment the value of 1 each time the loop execute

Line 5: End of the While End While Loop body

A while loop can be terminated when a break, goto, return, or throw


statement transfers control outside the loop. To pass control to the
next iteration without exiting the loop, use the continue statement.

Next :  How to use Enum in vb.net

Download Source Code


Print Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim counter As Integer
counter = 1
While (counter <= 10)
MsgBox("Counter Now is : " counter)
counter = counter + 1
End While
End Sub
End Class

When you execute the program 10 times the message shows with counter and exit
from the While .. End While loop. 

How to use Enum in vb.net


VB.NET Enum Example

When you are in a situation to have a number of constants that are


logically related to each other, you can define them together these
constants in an enumerator list. An enumerated type is declared
using the enum keyword.

Syntax:

Enum declaration

Enum Temperature
Low
Medium
High
End Enum

An enumeration has a name, an underlying data type, and a set of


members. Each member represents a constant. It is useful when
you have a set of values that are functionally significant and fixed.

Retrieve and check the Enum value

Dim value As Temperature = Temperature.Medium


If value = Temperature.Medium Then
Console.WriteLine("Temperature is Mediuam..")
End If

A simple Enum Excercise

Public Class Form1


Enum Temperature
Low
Medium
High
End Enum
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim value As Temperature = Temperature.Medium
If value = Temperature.Medium Then
MsgBox("Temperature is Mediuam..")
End If
End Sub
End Class

Initializing Members

By default the underlying type of each element in the enum is int. If


you do not specify initializer for a member, VB.Net initializes it
either to zero. If you try with above example to convert to integer
then you can see the result like the following:

Dim value As Temperature = Temperature.Medium


Dim val As Integer = CInt(value)
Console.WriteLine("Temperature value is.." + val)

Output is : Temperature value is..1

If you declare a different value in the first member of Enum then it


assign the next value greater by one than that of the immediately
preceding member. Check with the following program.

Public Class Form1


Enum Temperature
Low = 3
Medium
High
End Enum
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim value As Temperature = Temperature.Medium
Dim val As Integer = CInt(value)
MsgBox("Temperature value is.." + val.ToString)
End Sub
End Class

Output is : Temperature value is..4

You can specify another integral numeric type by using a colon. The
following Enum declare as byte, you can verify the underlying
numeric values by casting to the underlying type.

Enum Temperature As Byte


Low
Medium
High
End Enum

You can retrieve the value like the following:

Dim value As Temperature = Temperature.Medium


Dim val As Byte = CByte(value)
Console.WriteLine("Temperature value is.." + val);

How to get int value from enum

Private Enum Days


Sunday = 1
TuesDay = 2
wednesday = 3
End Enum
'get int val
Private day As Integer = CInt(Days.TuesDay)

Enum.Parse in VB.Net

Enum.Parse() converts the VB.Net string representation of the name


or integer value of one or more enumerated constants to an
equivalent Enum object.

String convert to Enum

Public Class Form1


Public Enum Colors
red
blue
green
yellow
End Enum
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim inVal As String = "green"
Dim newColor As Colors = DirectCast([Enum].Parse(GetType(Colors),
inVal), Colors)
'Check the Enum type
If newColor = Colors.green Then
MessageBox.Show(newColor.ToString())
End If
End Sub
End Class

Output is : green

How can an int value cast to enum

Following is the easiest method to cast an int to enum.

MyEnum myenum = (MyEnum)intvalue;

Ex:

Private Enum Days


Sunday = 1
TuesDay = 2
wednesday = 3
End Enum
//cast here
Private day As Days = DirectCast(3, Days)

Converts int to enum values

Method 2:

MyEnum myenum = (MyEnum)Enum.ToObject(typeof(MyEnum) ,


intvalue);

Dim day As Days = DirectCast([Enum].ToObject(GetType(Days), 3), Days)

You can check if it's in range using Enum.IsDefined

If [Enum].IsDefined(GetType(Days), day) Then


MessageBox.Show("Its in tange")
End If

How to Loop through all enum values in VB.Net

The VB.Net GetValues() returns an array that contains a value for


each value of the enum Type . If more than one members have the
same value, it will return array includes duplicate values

Iterating through an enum in vb.net

The following example will show how do enumerate an enum .

Public Class Form1


Public Enum Colors
red
blue
green
yellow
End Enum
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
For Each iColor As Colors In [Enum].GetValues(GetType(Colors))
MessageBox.Show(iColor.ToString())
Next
End Sub
End Class

Enum Flags Attribute

The idea of Enum Flags is to take an enumeration variable and allow


it hold multiple values. It should be used whenever the enum
represents a collection of flags, rather than representing a single
value. More about.... Enum Flags Explained

Convert an enum to a List

The following program shows how to convert an enum to List


Datastructure. More about.... Enum to List

Enum in Select Case

The following program shows how to use Enum in Select....Case


statement.

Next :  How to use IF ELSE END IF in VB.NET


Download Source Code

Print Source Code

Public Class Form1


Enum Temperature
Low
Medium
High
End Enum

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
Dim value As Temperature = Temperature.Medium
Select Case value
Case Temperature.Low
MessageBox.Show("Low Temperature")
Exit Select
Case Temperature.Medium
MessageBox.Show("Mediuam Temperature")
Exit Select
Case Temperature.High
MessageBox.Show("High Temperature")
Exit Select
End Select
End Sub
End Class

You might also like