1. Shri Shivaji Science College, Amravati
Department of Computer Science
Topic- Array in VB.NET
Prepared By
Dr. Ujwala S. Junghare
Assistant Professor
Dept. of Computer Science
2. An array stores a fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a collection of variables of
the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Creating Arrays in VB.Net
To declare an array in VB.Net, you use the Dim statement.
3. Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _ "Shivangi",
"Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
The elements in an array can be stored and accessed by using the index of the array.
The following program demonstrates this −
For example,
4. Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers ‘
Dim i, j As Integer ' initialize elements of array n ‘
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i ' output each array element's value ‘
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
5. In VB.NET, the control statements are the statements that controls the execution of the
program on the basis of the specified condition.
It is useful for determining whether a condition is true or not. If the condition is true, a single
or block of statement is executed.
In the control statement, we will use if- Then, if Then Else, if Then ElseIf and the Select
case statement.
We can define more than one condition to be evaluated by the program with statements. If the
defined condition is true, the statement or block executes according to the condition, and if the
condition is false, another statement is executed.
The following figure shows a common format of the decision control statements to validate
and execute a statement:
Controlling program flow, Conditional Statements
6. The above diagram shows that if the defined condition is true, statement_1 will be executed, and if the condition is
false, statement_2 will be executed.
VB.NET provides the following conditional or decision-making statements.
•If-Then Statement
•If-Then Else Statement
•If-Then ElseIf Statement
•Select Case Statement
•Nested Select Case Statements
7. If-Then Statement
The If-Then Statement is a control statement that defines one or more conditions, and if the particular
condition is satisfied, it executes a piece of information or statements.
Syntax:
If condition Then
[Statement or block of Statement]
End If
In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and the statement
can be single or group of statements that will be executed when the condition is true.
8. Example 1: Write a simple program to print a statement in VB.NET.
Module1.vb
Module Module1
' Declaration of variable str
Dim str As String = "JavaTpoint"
Sub Main()
' if str equal to "JavaTpoint", below Statement will be executed.
If str = "JavaTpoint" Then
Console.WriteLine("Welcome to the JavaTpoint")
End If
Console.WritLine("press any key to exit?")
Console.ReadKey()
End Sub
End Module
9. If-Then-Else Statement
The If-Then Statement can execute single or multiple statements when the condition is true, but when
the expression evaluates to false, it does nothing. So, here comes the If-Then-Else Statement.
The IF-Then-Else Statement is telling what If condition to do when if the statement is false, it executes
the Else statement. Following is the If-Then-Else statement syntax in VB.NET as follows:
Syntax:
If (Boolean_expression) Then
'This statement will execute if the Boolean condition is true
Else
'Optional statement will execute if the Boolean condition is false
End If
10. Module decisions
Sub Main() 'local variable definition ‘
Dim a As Integer = 100
If (a < 20) Then
Console.WriteLine("a is less than 20")
Else
Console.WriteLine("a is not less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
11. If . . . Then . . . ElseIf is similar to If . . . Then . . . Else, except that it offers a number of choices.
The construct is used as follows:
If Condition1 Then
Statement1
ElseIf Condition2 Then
Statement2
.
.
ElseIf Conditionk Then
Statementk
End If
The program will examine each condition in turn until it finds a condition that is true. Once a true
condition is found, and its statement has been executed, the program terminates the conditional
search at End If. If none of the conditions are true, a default condition can be provided by adding a
final Else section. The default condition must be the last in the list, and its associated statement will
be executed only if none of the other conditions are true.
The If . . . Then . . . ElseIf statement
If(condition 1)Then
' Executes when condition 1 is true
ElseIf( condition 2)Then
' Executes when condition 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the condition 3 is true
Else
' executes the default statement when none of the above conditions i
s true.
End If
12. The following diagram represents the functioning of the If-Else-If Statement in the VB.NET programming
language.
13. Private Sub Form1_Click (sender As Object, e As EventArgs) Handles Me.Click
If BackColor = Color.Red Then
BackColor = Color.Blue
ElseIf BackColor = Color.Blue Then
BackColor = Color.Green
ElseIf BackColor = Color.Green Then
BackColor = Color.Black
Else
BackColor = Color.Red
End If
End Sub
14. Module if_elseIf
Sub Main()
Dim var1 As Integer
Console.WriteLine(" Input the value of var1: ")
var1 = Console.ReadLine()
If var1 = 20 Then
'if condition is true then print the following statement'
Console.WriteLine(" Entered value is equal to 20")
ElseIf var1 < 50 Then
Console.WriteLine(" Entered value is less than 50")
ElseIf var1 >= 100 Then
Console.WriteLine(" Entered value is greater than 100")
Else
'if none of the above condition is satisfied, print the following statement
Console.WriteLine(" Value is not matched with above condition")
End If
Console.WriteLine(" You have entered : {0}", var1)
Console.WriteLine(" press any key to exit...")
Console.ReadKey()
End Sub
End Module
15. A Select Case statement allows a variable to be tested for equality against a list of values. Each value is called
a case, and the variable being switched on is checked for each select case.
The syntax for a Select Case statement in VB.Net is as follows −
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Where,
expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char,
Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort.
expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are
separated by commas.
statements − statements following Case that run if the select expression matches any clause in expressionlist.
elsestatements − statements following Case Else that run if the select expression does not match any clause in
the expressionlist of any of the Case statements.
Select Case
16.
17. Module decisions
Sub Main()
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module
18. Module Module1
Sub Main()
Dim name As String
name = “Good"
Select Case name
Case "John"
Console.WriteLine("Hello John")
Case "Ggg11"
Console.WriteLine("Hello Ggg11")
Case "Alice"
Console.WriteLine("Hello Alice")
Case "Joel"
Console.WriteLine("Hello Joel")
Case Else
Console.WriteLine("unknown name")
End Select
Console.WriteLine("VB.NET is easy!")
Console.ReadKey()
End Sub
End Module
19. VB.Net - Loops
Loop in the programming language may be defined as the iteration of a
particular set of code until it meets the specified condition.VB.Net Loops is
followed by the line of statements that has to be executed recursively. It helps
in reducing the line of codes as one line of code can be executed multiple times
based on the requirement.
Types of Loops
There are five types of loops available in VB.NET:
Do While Loop
For Next Loop
For Each Loop
While End Loop
With End Loop
20. Do While Loop
In VB.NET, Do While loop is used to execute blocks of statements in the program, as
long as the condition remains true. It is similar to the While End Loop, but there is
slight difference between them. The while loop initially checks the defined condition,
if the condition becomes true, the while loop's statement is executed. Whereas in
the Do loop, is opposite of the while loop, it means that it executes the Do statements,
and then it checks the condition.
Do
[ Statements to be executed]
Loop While Boolean_expression
// or
Do
[Statement to be executed]
Loop Until Boolean_expression
21. Module Do_loop
Sub Main()
' Initializatio and Declaration of variable i
Dim i As Integer = 1
Do
' Executes the following Statement
Console.WriteLine(" Value of variable I is : {0}", i)
i = i + 1 'Increment the variable i by 1
Loop While i <= 10 ' Define the While Condition
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
22. While... End While Loop
It executes a series of statements as long as a given condition is True.
The syntax for this loop construct is −
While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While
Here, statement(s) may be a single statement or a block of statements. The
condition may be any expression, and true is logical true. The loop iterates while
the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
23. Module loops
Sub Main()
Dim a As Integer = 10
' while loop execution '
While a < 20
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
Console.ReadLine()
End Sub
End Module
Here, key point of the While loop is that the
loop might not ever run. When the condition is
tested and the result is false, the loop body will
be skipped and the first statement after the
while loop will be executed.
24. 1. For Next Loop
For Next loop is the most frequently used loop in Vb.net. It usually checks the condition
and if it is satisfied, it lets the codes mentioned under its body execute else moves to
the next condition. It is used to perform the interaction for particular tasks for a number
of times. The next loop is available in all of the programming languages but the system
and the keywords vary.
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
25. Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module
26. for Each statements
Repeats a group of statements for each element in a collection.
Syntax
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
elementRequired in the For Each statement. Optional in the Next statement.
Variable. Used to iterate through the elements of the collection.
datatypeOptional if Option Infer is on (the default) or element is already declared;
required if Option Infer is off and element isn't already declared. The data type
of element.
27. Group--Required. A variable with a type that's a collection type or Object. Refers to the collection
over which the statements are to be repeated.
Statements--Optional. One or more statements between For Each and Next that run on each item
in group.
Continue For--Optional. Transfers control to the start of the For Each loop.
Exit For--Optional. Transfers control out of the For Each loop.
Next--Required. Terminates the definition of the For Each loop.
' Create a list of strings by using a ' collection initializer.
Dim lst As New List(Of String) _ From {"abc", "def", "ghi"}
' Iterate through the list.
For Each item As String In lst
Debug.Write(item & " ")
Next
Debug.WriteLine("")
'Output: abc def ghi
28. The GoTo statement transfers control unconditionally to a specified line in a procedure.
The syntax for the GoTo statement is −
GoTo label
Module loops
Sub Main() ' local variable definition
Dim a As Integer = 10
Line1:
Do
If (a = 15) Then
' skip the iteration
a = a + 1
GoTo Line1
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
29. The Continue statement causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating. It works somewhat like the Exit
statement. Instead of forcing termination, it forces the next iteration of the loop to take
place, skipping any code in between.
For the For...Next loop, Continue statement causes the conditional test and increment
portions of the loop to execute. For the While and Do...While loops, continue statement
causes the program control to pass to the conditional tests.
Syntax
The syntax for a Continue statement is as follows −
Continue { Do | For | While }
Continue statement
30. Live Demo
Module loops Sub Main()
' local variable definition
Dim a As Integer = 10
Do
If (a = 15) Then
= a + 1
Continue
Do
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1 Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
31. Exit Statement
The Exit statement transfers the control from a procedure or block immediately to the
statement following the procedure call or the block definition. It terminates the loop,
procedure, try block or the select block from where it is called.
If you are using nested loops (i.e., one loop inside another loop), the Exit statement will
stop the execution of the innermost loop and start executing the next line of code after the
block.
Syntax
The syntax for the Exit statement is −
Exit { Do | For | Function | Property | Select | Sub | Try | While }
32. Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
' while loop execution '
While (a < 20)
Console.WriteLine("value of a: {0}", a)
a = a + 1
If (a > 15) Then
‘terminate the loop using exit statement
Exit While
End If
End While
Console.ReadLine()
End Sub
End Module
33. Handling Exceptions
There are two ways of handling errors that occur at run time in VB .NET—with
structured and unstructured exception handling.
Exceptions are just runtime errors; in Visual Basic (unlike some other languages), the
terms exception handling and error handling have become inter-changeable.
Exceptions ,occur when a program is running (as opposed to syntax errors, which
will prevent VB .NET from running your program at all). You can trap such
exceptions and recover from them, rather than letting them bring your program to an
inglorious end.
34. Unstructured Exception Handling
The old error-handling mechanism in VB6 and before is now called unstructured exception
handling, and it revolves around the On Error Goto statement. You use this statement to tell
VB .NET where to transfer control to in case there's been an exception,
as in this case, where I'm telling Visual Basic to jump to the label "Handler" if there's been an
exception. You create labels in your code with the label name followed by a colon, and the
exception-handling code will follow that label (note that I've added an Exit
Sub statement to make sure the code in the exception handler is not executed by mistake
as part of normal program execution):
Module Module1
Sub Main()
On Error Goto Handler
⋮
Exit Sub
Handler:
⋮
End Sub
End Module
35. Suppose I execute some code that may cause an exception, as here, where the code performs a
division by zero, which causes an exception. When the exception occurs, control will jump to the
exception handler, where I'll display a message and then use the Resume Next statement to
transfer control back to the statement immediately after the statement that caused the
exception:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
On Error Goto Handler
int3 = int2 / int1
System.Console.WriteLine("The answer is {0}", int3)
Handler:
System.Console.WriteLine("Divide by zero error")
Resume Next
End Sub
End Module
When you run this code, you see this message:
Divide by zero error
36. Structured Exception Handling
Microsoft has added structured exception handling to Visual Basic, and as you might expect, it's now
considered the recommended method of exception handling. In fact, it is appropriate to call the On Error
GoTo method of exception handling unstructured, because using this statement just sets the internal
exception handler in Visual Basic; it certainly doesn't add any structure to your code, and if your code
extends over procedures and blocks, it can be hard to figure out what exception handler is working
when.
Visual Basic also supports structured exception handling. In particular, Visual Basic uses an enhanced
version of the Try…Catch…Finally.
Try − A Try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more Catch blocks.
Catch − A program catches an exception with an exception handler at the place in a program where
you want to handle the problem. The Catch keyword indicates the catching of an exception.
Finally − The Finally block is used to execute a given set of statements, whether an exception is thrown
or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
Throw − A program throws an exception when a problem shows up. This is done using a Throw
keyword.
37. Try…Catch…Finally statement looks like in general:
Try
[ tryStatements ]
[Catch [ exception1 [ As type1 ] ] [ When expression1 ]
catchStatements1
[Exit Try] ]
[Catch [ exception2 [ As type2 ] ] [When expression2 ]
catchStatements2
[ Exit Try ] ]
⋮
[Catch [ exceptionn [ As typen ] ] [ When expressionn ]
catchStatementsn ]
[ Exit Try ] ]
[ Finally
[ finallyStatements ]
End Try
38. Exception Classes in .Net Framework
In the .Net Framework, exceptions are represented by classes. The exception classes in .Net
Framework are mainly directly or indirectly derived from the System.Exception class. Some of the
exception classes derived from the System.Exception class are
the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So
the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class −
39. Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method refers to an
array index out of range.
System.ArrayTypeMismatchExcepti
on
Handles errors generated when type is mismatched with
the array type.
System.NullReferenceException Handles errors generated from deferencing a null object.
System.DivideByZeroException Handles errors generated from dividing a dividend with
zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException Handles errors generated from insufficient free memory.
System.StackOverflowException Handles errors generated from stack overflow.
40. Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try result = num1 num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
Output:
Exception caught: System.DivideByZeroException: Attempted to
divide by zero. at ... Result: 0