Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

UNIT-II

 VB.NET Conditional Statement (Decision Making) Statements


Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
Decision Making Statement allows user to choose one path from the two or
more execution path on the basis of condition. If the condition is true then one set
of statement will be executed and if the condition is false another set of statement
will be executed.
A basic diagram for decision making statement is given below:

VB.NET includes following conditional (decision making) statements:


1) Simple If statement
2) If..Then..Else statement
3) If..Then..Else if..Else statement
4) Nested If statement
5) Select….Case statement
1. Simple 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.

VB.NET BY PROF.A.D.CHAVAN Page 1


UNIT-II

Here is the syntax of if statement given below:


If condition Then
Statement –block a;
End if
Statement-block b;
Where, condition is a Boolean or relational condition and Statement(s) is a
simple or compound statement.
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:

Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 10
' check the boolean condition using if statement
If (a < 20) Then
' if condition is true then print the following
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()

VB.NET BY PROF.A.D.CHAVAN Page 2


UNIT-II

End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a is less than 20
value of a is : 10
2.The If..Then..Else statement
If..Then..Else statement contains the two blocks If block and Else block.
When condition present in parenthesis of If statement is true then statements of if
block executed and if condition is false then statements of Else block executed.
The general structure of an If..Then..Else statement is as follows:
If condition Then
Statement-block 1;
Else
Statement-block2;
End If
Statement-block n;
In the above syntax if condition is true then “Statement-block 1” will be
executed followed by “Statement-block n” and if condition is false then
“Statement-block 2” will be executed followed by “Statement-block n”. You can
easily understand the concept by following diagram:

EXAMPLE
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100

VB.NET BY PROF.A.D.CHAVAN Page 3


UNIT-II

' check the boolean condition using if statement


If (a < 20) Then
' if condition is true then print the following
Console.WriteLine("a is less than 20")
Else
' if condition is false then print the following
Console.WriteLine("a is not less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a is not less than 20
value of a is : 100
3.If..Then..ElseIf..Else statement
The If..Then..ElseIf…Else statement is very useful in the case where user
want to select a option from multiple options. In this type of statement ‘ If’ is
followed by one or more ElseIf statements and finally end with a Else statement.
The basic syntax of the If..Then…ElseIf ..Else statement is given below:
If condition-1 Then
Statement-block 1
ElseIf condition-2 Then
Statement-block 2
ElseIf condition-3 Then
Statement-block 3
Else
Statement-block a
End If
Statement-block b
In the above syntax, if condition-1 is true then Statement-block 1 will be
executed followed by Statement-block b, and if condition-1 is false then program
control will check condition-2 if it is is true then Statement-block 2 will be
executed followed by Statement-block b and if condition-2 is false then program
control will check condition-3 if it is true then Statement-block 3 will be executed
followed by Statement-block b and if condition-3 is also false then Statement-
block a will be executed followed by Statement-block b. You can understand this
concept by following diagram:

VB.NET BY PROF.A.D.CHAVAN Page 4


UNIT-II

NOTE: An If..Then..ElseIf..Else statement can contain any number of ElseIf


statements.
4.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..Else If..Else, If..Then..Else statements inside the other If,
Else If or Else statements that is known 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

VB.NET BY PROF.A.D.CHAVAN Page 5


UNIT-II

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:

5. Select…Case Statement
The Select…Case statement in VB.NET is used to select and execute one of
the many groups of statements on the basis of the value of the expression in the
condition.
The syntax of the Select…Case statement is given below:
Select [Case] (test expression)
Case value-1
Statement-block 1
Case value-2
Statement -block 2
……………………………..
……………………………..
Case Else
Statement-block N
End Select
Statement-block x
Select statement checks the value of the expression against a list of case value
and when a match is found, a block of statements associated with that Case are

VB.NET BY PROF.A.D.CHAVAN Page 6


UNIT-II

executed and when the match is not found then the statements associated with Case
Else are executed. You can understand this concept by the following diagram:

Example
Module decisions
Sub Main()
'local variable definition
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
When the above code is compiled and executed, it produces the following result:
Well done
Your grade is B

VB.NET BY PROF.A.D.CHAVAN Page 7


UNIT-II

Module Module1
Sub Main()
Dim value As Integer = Integer.Parse(Console.ReadLine())
Select Case value
Case 1
Console.WriteLine("You typed one")
Case 2
Console.WriteLine("You typed two")
Case 5
Console.WriteLine("You typed five")
Case Else
Console.WriteLine("You typed something else")
End Select
End Sub
End Module
Output
2
You typed two
 VB.NET Loop Statement
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Loops are used to execute a group of statements repetitively on the basis of
some condition. The statement present in the Loop body is executed repetitively
until specified condition gets false as soon as condition gets false program control
comes outside the loop body and the statement present immediate after the loop’s
body gets executed.
The following diagram shows the concept of Loop:

VB.NET BY PROF.A.D.CHAVAN Page 8


UNIT-II

In VB.NET following loops are present:


• For…Next Loop
• Do Loop
• While…End While Loop
1. For...Next Loop
For...Next Loop is used to execute a group of statements repeatedly for a
specified number of times Next statement in For..Next loop increments the value
of loop-counter.
The basic syntax of For..Next loop is given here:
For counter [As datatype] = start To end [Step step]
[Statements]
[Exit For]
[Statements]
Next[counter]
You can understand the concept of For..Next loop by the following diagram:

PROGRAM FOR Print no 1 to 5


Module Module1
Sub Main ()
Dim i As Integer
For i = 1 To 5
Console.Write(i.ToString + " ")
Next i
Console.ReadLine()
End Sub
End Module
OUTPUT
12345

VB.NET BY PROF.A.D.CHAVAN Page 9


UNIT-II

Using the For Each…Next Loop


You use the For Each…Next loop to loop over elements in an array or a
Visual Basic collection. This loop is great, because it automatically loops over all
the elements in the array or collection—you don't have to worry about getting the
loop indices just right to make sure you get all elements, as you do with a For
loop. Here's the syntax of this loop:
For Each element in group
[statements]
[Exit For]
[statements]
Next [element]
You can get a look at this loop in action with an example like this, in which I'm
displaying all the elements of an array:
Module Module1
Sub Main()
Dim intIDArray(3), intArrayItem As Integer
intIDArray(0) = 0
intIDArray(1) = 1
intIDArray(2) = 2
intIDArray(3) = 3
For Each intArrayItem In intIDArray
System.Console.WriteLine(intArrayItem)
Next intArrayItem
End Sub
End Module
And here's the result of this code:
0
1
2
3
Press any key to continue
2. Do Loop
Do loop is used to execute a group of statements repeatedly as long as the
condition is true or until the condition becomes true.
The basic syntax of the Do Loop is given below:
Do {while | Until} condition
[Statements]
[Exit Do]
[Statements]
Loop
VB.NET BY PROF.A.D.CHAVAN Page 10
UNIT-II

OR
Do
[Statements]
[Exit Do]
[Statements]
Loop {While | Until} condition
You can understand the concept of Do loop by the following diagram:

Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a=a+1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
VB.NET BY PROF.A.D.CHAVAN Page 11
UNIT-II

value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
The program would behave in same way, if you use an Until statement, instead of
While:
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a=a+1
Loop Until (a = 20)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
3. While...End While Loop
While…End While Loop repeatedly executes a set of statement as long as a
specified condition is true. While statement always checks the condition first
before executing the statements present in loop-body. When the control reaches the
End While statement, the control is passed back to the While statement. If
condition is still true, the statements inside the loop body are executed else exits
the loop.
The basic syntax of While.. End While Loop is as follows:

VB.NET BY PROF.A.D.CHAVAN Page 12


UNIT-II

While condition
[Statements]
End While
You can understand the concept of While..End While loop by the following
diagram:

PROGRAM FOR FACTORIAL OF N USING WHILE


Module module1
Sub Main()
Dim n, fact As Integer
Console.WriteLine("enter a number")
n = CInt(Console.ReadLine())
fact = 1
While n > 0
fact = fact * n
n=n-1
End While
Console.WriteLine("FACTORIAL = " + fact.ToString())
Console.Read()
End Sub
End Module
OUTPUT
Enter a number
5
FACTORIAL = 120
4.The With Statement
The With statement is not a loop, properly speaking, but it can be as useful
as a loop—and in fact, many programmers actually think of it as a loop. You use

VB.NET BY PROF.A.D.CHAVAN Page 13


UNIT-II

the with statement to execute statements using a particular object. Here's the
syntax:
With object
[statements]
End With
Here's an example showing how to put with to work. Here, I'm use a text
box, Text1, in a Windows form program, and setting its Height, Width, and Text
properties in the with statement:
With TextBox1
.Height = 1000
.Width = 3000
.Text = "Welcome to Visual Basic"
End With
5.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 }
Flow Diagram

EXAMPLE
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10

VB.NET BY PROF.A.D.CHAVAN Page 14


UNIT-II

' 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
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
6.Continue Statement
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 }
Flow Diagram

VB.NET BY PROF.A.D.CHAVAN Page 15


UNIT-II

Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
Do
If (a = 15) Then
' skip the iteration '
a=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
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
7.GoTo Statement
The GoTo statement transfers control unconditionally to a specified line in a
procedure
.
The syntax for the GoTo statement is:
GoTo label
Flow Diagram

VB.NET BY PROF.A.D.CHAVAN Page 16


UNIT-II

Example
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
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

VB.NET BY PROF.A.D.CHAVAN Page 17


UNIT-II

 VB.Net - Arrays
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. For example,
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:
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
When the above code is compiled and executed, it produces the following result:

VB.NET BY PROF.A.D.CHAVAN Page 18


UNIT-II

Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
1.Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par
the need of the program. You can declare a dynamic array using the ReDim
statement.
Syntax for ReDim statement:
ReDim [Preserve] arrayname(subscripts)
Where,
 The Preserve keyword helps to preserve the data in an existing array, when
you resize it.
 arrayname is the name of the array to re-dimension.
 subscripts specifies the new dimension.
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
ReDim Preserve marks(10)
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
VB.NET BY PROF.A.D.CHAVAN Page 19
UNIT-II

End Sub
End Module
When the above code is compiled and executed, it produces the following result:
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
2.Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also
called rectangular arrays.
You can declare a 2-dimensional array of strings as:
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables:
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional array:
Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
VB.NET BY PROF.A.D.CHAVAN Page 20
UNIT-II

a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
3.Jagged Array
A Jagged array is an array of arrays. The follwoing code shows declaring a
jagged array named scores of Integers:
Dim scores As Integer()() = New Integer(5)(){}
The following example illustrates using a jagged array:
Module arrayApl
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer
' output each array element's value
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
VB.NET BY PROF.A.D.CHAVAN Page 21
UNIT-II

a[4][0]: 4
a[4][1]: 8
 VB.NET Exceptional Handling
An exception can be considered as an error which is caused due to a run
time error in a program. When the compiler encounters with the error such as
dividing by zero, it creates an exception object and informs us that an error has
occurred.
If we want that the program remains continue executing the remaining code,
we have to Catch the exception object thrown by the error condition and display an
appropriate message for taking corrective action. This process is known as the
exception handling. If we do not Catch and handle the exception object properly
the compiler will display an error message and will terminate the program.
In VB.NET 2010 Exception can be divided into two parts:
now we are going to discuss some important terms regarding exception handling:
1.Try block: The code that may be throw exception which we want to handle is
put in the Try block. It is followed by one and more Catch block.
Try Block
Try block—you put the exception-prone code in the Try section and the
exception-handling code in the Catch section:
Module Module1
Sub Main()
Try

Catch e As Exception

End Try
End Sub
End Module
Note the syntax of the Catch statement, which catches an Exception object
that I'm naming e. When the code in the Try block causes an exception, I can use
the e.ToString method to display a message:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
Try
int3 = int2 / int1
System.Console.WriteLine("The answer is {0}", int3)
Catch e As Exception
System.Console.WriteLine(e.ToString)

VB.NET BY PROF.A.D.CHAVAN Page 22


UNIT-II

End Try
End Sub
End Module
Here's what you see when you run this code:
System.OverflowException: Exception of type System.OverflowException was
thrown. at Microsoft.VisualBasic.Helpers.IntegerType.FromObject(Object Value)
at ConsoleHello.Module1.Main() in C:\vbnet\ConsoleHello\Module1.vb:line 5
Besides using the e.ToString method, you can also use the e.message field, which
contains this message:
Exception of type System.OverflowException was thrown.
2. Catch block: The code to handle the thrown exception is put in the Catch
block just after the Try block.
Using Multiple Catch Statements
You also can use multiple Catch statements when you filter exceptions. Here's
an example that specifically handles overflow, invalid argument, and argument out
of range exceptions:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
Try
int3 = int2 / int1
System.Console.WriteLine("The answer is {0}", int3)
Catch e As System.OverflowException
System.Console.WriteLine("Exception: Arithmetic overflow!")
Catch e As System.ArgumentException
System.Console.WriteLine("Exception: Invalid argument value!")
Catch e As System.ArgumentOutOfRangeException
System.Console.WriteLine("Exception: Argument out of range!")
End Try
End Sub
End Module
If you want to add a general exception handler to catch any exceptions not
filtered, you can add a Catch block for the Exception class at the end of the other
Catch blocks:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
Try
int3 = int2 / int1

VB.NET BY PROF.A.D.CHAVAN Page 23


UNIT-II

System.Console.WriteLine("The answer is {0}", int3)


Catch e As System.ArgumentOutOfRangeException
System.Console.WriteLine("Exception: Argument out of range!")
Catch e As System.ArgumentException
System.Console.WriteLine("Exception: Invalid argument value!")
Catch e As Exception
System.Console.WriteLine("Exception occurred!")
End Try
End Sub
End Module
3.Finally block: Finally block is always executed whether the exception is thrown
or not by the Try block
Using Finally
The code in the Finally block, if there is one, is always executed in a
Try…Catch…Finally statement, even if there was no exception, and even if you
execute an Exit Try statement. This allows you to deallocate resources and so on;
here's an example with a Finally block:
Module Module1
Sub Main()
Dim int1 = 0, int2 = 1, int3 As Integer
Try
int3 = int2 / int1
System.Console.WriteLine("The answer is {0}", int3)
Catch e As System.OverflowException
System.Console.WriteLine("Exception: Arithmetic overflow!")
Catch e As System.ArgumentException
System.Console.WriteLine("Exception: Invalid argument value!")
Catch e As System.ArgumentOutOfRangeException
System.Console.WriteLine("Exception: Argument out of range!")
Finally
System.Console.WriteLine("Execution of sensitive code " & _
"is complete")
End Try
End Sub
End Module
And here's what you see when you execute this console application:
Exception: Arithmetic overflow!
Execution of sensitive code is complete
4. Throw statement: Any method can throw the exception using Throw statement

VB.NET BY PROF.A.D.CHAVAN Page 24


UNIT-II

when any unexpected event is occur.


Throwing an Exception
You can throw an exception using the Throw statement, and you can also
rethrow a caught exception using the Throw statement. Here's an example where
I'm explicitly throwing an overflow exception:
Module Module1
Sub Main()
Try
Throw New OverflowException()
Catch e As Exception
System.Console.WriteLine(e.Message)
End Try
End Sub
End Module
 Standard Exceptions
The exceptions which are pre-defined and provide us with the help of some
classes called Exception classes by .NET Class Library are known as Standard
Exceptions. These Exception classes are defined in the System namespace.Some
of the exception classes present in .NET class library are given below in the table:
Handling Standard Exceptions using Try-Catch block
•The piece of code to handle the exception is written in the Try-Catch block.
•When a program starts executing, the program control enters the Try block. If all
the statements present in Try block successfully executed, then the program
control leaves the Try-Catch block.
•If any statement fails to execute, the execution of remaining statements is stopped
and the program control goes to the Catch block for handling the exception.
Some facts about Try-Catch block
•A Try block must be followed by a Catch block.
•A Try block can have multiple Catch blocks.
•The Try block must lie inside a method.
Here is an example of handling exceptions using Try-Catch block:
Example:
1)Open Microsoft Visual Studio 2010.
2)Click on File|New Project option. A New Project dialog box will appear.
3)Now select Visual Basic language and Windows Form Application from the
pane and named the application as Exceptions.
4)Now add two TextBox controls and a Button control on the form from the
ToolBox.
5)Change the Text property of Button1 control to Divide.

VB.NET BY PROF.A.D.CHAVAN Page 25


UNIT-II

6)Double click on the Form to open its code window and add the following code
in it:
Public Class Form1
Public Sub Divison(ByVal x As Integer, ByVal y As Integer)
Dim z As String
Try
x=x/y
z = Convert.ToString(x)
MessageBox.Show(z)
Catch de As DivideByZeroException
MessageBox.Show("Cannot divide by zero." + "This is a Logical Error" &
de.ToString())
End Try
End Sub
End Class
7)Now double click on the Divide button and add the following code in its code
window:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)
Handles Button1.Click
Dim p, q As Integer
p = Convert.ToInt32(TextBox1.Text)
q = Convert.ToInt32(TextBox2.Text)
Divison(p, q)
End Sub
End Class
8)Run the application by pressing F5 key. Now this will shows a form as given in
the following diagram:
9)Now enter 10 in first textbox and 0 in second textbox this will shows the
following result:
 User-Defined Exceptions
Sometimes a situation is arises that we have to handle an exception for
which there is no exception class defined in the .NET class library. In that cases
we are called the classes as user-defined classes and the exception handled by
these classes are known as user-defined exceptions.
Handling User-Defined Exceptions
Here is an example which shows the handling of user-defined exceptions:
Example
1)Open Microsoft Visual Studio 2010.
2)Click on File|New Project option. A New Project dialog box will appear.

VB.NET BY PROF.A.D.CHAVAN Page 26


UNIT-II

3)Now select Visual Basic language and Console Application from the pane and
named the application as UserDefinedExceptions.
4)Now add the following code in code window:
Module Module1
Sub Main()
Dim x, y As Integer
x=3
y = 15000
Try
Dim z As Single
z = Convert.ToString(x / y)
If z < 0.001 Then
Throw New myexception("number is very small")
End If
Catch ex As myexception
Console.WriteLine("exception caught")
Console.WriteLine(ex.message)
Finally
Console.WriteLine("Control entered in Finally block")
Console.Read()
End Try
End Sub
Class myexception
Inherits Exception
Public Sub New()
End Sub
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
Public Sub New(ByVal message As String, ByVal inner As Exception)
MyBase.New(message, inner)
End Sub
End Class
End Module
5)Now run the application by pressing F5 key this will produce following output:

VB.NET BY PROF.A.D.CHAVAN Page 27


UNIT-II

 Sub procedures
Sub procedures are procedures that do not return any value. We have been
using the Sub procedure Main in all our examples. We have been writing console
applications . When these applications start, the control goes to the Main Sub
procedure, and it in turn, runs any other statements constituting the body of the
program.
Defining Sub Procedures
The Sub statement is used to declare the name, parameter and the body of a
sub procedure. The syntax for the Sub statement is:
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
 Modifiers: specify the access level of the procedure; possible values are:
Public, Private, Protected, Friend, Protected Friend and information
regarding overloading, overriding, sharing, and shadowing.
 SubName: indicates the name of the Sub
 ParameterList: specifies the list of the parameters
Example
The following example demonstrates a Sub procedure CalculatePay that takes two
parameters hours and wages and displays the total pay of an employee:
Module mysub
Sub CalculatePay(ByVal hours As Double, ByVal wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage

VB.NET BY PROF.A.D.CHAVAN Page 28


UNIT-II

Console.WriteLine("Total Pay: {0:C}", pay)


End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00
Passing Parameters by Value
This is the default mechanism for passing parameters to a method. In this
mechanism, when a method is called, a new storage location is created for each
value parameter. The values of the actual parameters are copied into them. So, the
changes made to the parameter inside the method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword. The
following example demonstrates the concept:
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
VB.NET BY PROF.A.D.CHAVAN Page 29
UNIT-II

End Module
When the above code is compiled and executed, it produces the following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside
the function.
Passing Parameters by Reference
A reference parameter is a reference to a memory location of a variable.
When you pass parameters by reference, unlike value parameters, a new storage
location is not created for these parameters. The reference parameters represent the
same memory location as the actual parameters that are supplied to the method.
In VB.Net, you declare the reference parameters using the ByRef keyword. The
following example demonstrates this:
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
VB.NET BY PROF.A.D.CHAVAN Page 30
UNIT-II

Specifying Optional Procedure Arguments


You also can make arguments optional in VB .NET procedures if you use the
Optional keyword when declaring those arguments. Note that if you make one
argument optional, all the following arguments must also be optional, and you
have to specify a default value for each optional argument (although you can set
them to the keyword Nothing if you wish). You specify a default value with =
default_value in the procedure's argument list. Here's an example where I'm
making the string argument you pass to a Sub procedure named DisplayMessage
optional, and giving that argument the default value "Hello from Visual
Basic.NET":
Module Module1
Sub Main()
DisplayMessage()
End Sub
Sub DisplayMessage(Optional ByVal strText As String = _ "Hello from Visual
Basic.NET")
System.Console.WriteLine(strText)
End Sub
End Module
Now when I call DisplayMessage with no arguments, as in the code above, the
default value is used and this code displays:
Hello from Visual Basic.NET
 Functions
A procedure is a group of statements that together perform a task when
called. After the procedure is executed, the control returns to the statement calling
the procedure. VB.Net has two types of procedures:
 Functions
 Sub procedures or Subs
Functions return a value, whereas Subs do not return a value.
Defining a Function
The Function statement is used to declare the name, parameter and the body of a
function.
The syntax for the Function statement is:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Where,
 Modifiers: specify the access level of the function; possible values are:
Public, Private, Protected, Friend, Protected Friend and information
regarding overloading, overriding, sharing, and shadowing.
VB.NET BY PROF.A.D.CHAVAN Page 31
UNIT-II

 FunctionName: indicates the name of the function


 ParameterList: specifies the list of the parameters
 ReturnType: specifies the data type of the variable the function returns
Example
Following code snippet shows a function FindMax that takes two integer values
and returns the larger of the two.
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End Function
 Function Returning a Value
In VB.Net, a function can return a value to the calling code in two ways:
 By using the return statement
 By assigning the value to the function name
The following example demonstrates using the FindMax function:
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer
res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
VB.NET BY PROF.A.D.CHAVAN Page 32
UNIT-II

End Module
When the above code is compiled and executed, it produces the following result:
Max value is : 200
Recursive Function
A function can call itself. This is known as recursion. Following is an example that
calculates factorial for a given number using a recursive function:
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
MsgBox Function
MsgBox function can be used to display message to user, Displays a message box
that can contain text, buttons, and symbols to inform the user.
Function MsgBox(Prompt As Object [, Buttons As MsgBoxStyle =
MsgBoxStyle.OKOnly [, Title As Object = Nothing]])
Here are the arguments you pass to this function:
 Prompt—A string expression displayed as the message in the dialog box.
The maximum length is about 1,024 characters (depending on the width of
the characters used).
 Buttons—The sum of values specifying the number and type of buttons to
display, the icon style to use, the identity of the default button, and the
VB.NET BY PROF.A.D.CHAVAN Page 33
UNIT-II

modality of the message box. If you omit Buttons, the default value is zero.
See below.
 Title—String expression displayed in the title bar of the dialog box. Note
that if you omit Title, the application name is placed in the title bar.
You can find the possible constants to use for the Buttons argument in Table 1.
Table 1: MsgBox constants.
Constant Value Description
OKOnly 0 Shows OK button only.
OKCancel 1 Shows OK and Cancel buttons.
AbortRetryIgnore 2 Shows Abort, Retry, and Ignore buttons.
YesNoCancel 3 Shows Yes, No, and Cancel buttons.
YesNo 4 Shows Yes and No buttons.
RetryCancel 5 Shows Retry and Cancel buttons.
Critical 16 Shows Critical Message icon.
Question 32 Shows Warning Query icon.
Exclamation 48 Shows Warning Message icon.
Information 64 Shows Information Message icon.
DefaultButton1 0 First button is default.
DefaultButton2 256 Second button is default.
DefaultButton3 512 Third button is default.
ApplicationModal 0 Application modal, which means the user must
respond to the message box before continuing
work in the current application.
SystemModal 4096 System modal, which means all applications
are unavailable until the user dismisses the
message box.
MsgBoxSetForeground 65536 Specifies the message box window as the
foreground window.
MsgBoxRight 524288 Text will be right-aligned.
MsgBoxRtlReading 1048576 Specifies text should appear as right-to-left on
RTL systems such as Hebrew and Arabic.

VB.NET BY PROF.A.D.CHAVAN Page 34


UNIT-II

Note also that this function returns a value from the MsgBoxResult
enumeration. Here are the possible MsgBoxResult values, indicating which button
in the message box the user clicked:
 OK
 Cancel
 Abort
 Retry
 Ignore
 Yes
 No
For example, here's how we use MsgBox in the MsgAndInput example. In
this case, I'm adding OK and Cancel buttons to the message box, adding an
information icon, and making the message box modal (which means you have to
dismiss it before doing anything else). And I also check to see if the user clicked
the OK button, in which case I display the message "You clicked OK" in a text
box:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim Result As Integer
Result = MsgBox("This is a message box!", MsgBoxStyle.OKCancel +
MsgBoxStyle.Information + MsgBoxStyle.SystemModal, "Message Box")
If (Result = MsgBoxResult.OK) Then
TextBox1.Text = "You clicked OK"
End If
End Sub
You can see the results of this code in Below Figure

Figure : A message box created with the MsgBox function.


Using the MessageBox.Show Method
In addition to the MsgBox function (see the previous topic), you can use the
.NET framework's MessageBox class's Show method to display message boxes.
This method has many overloaded forms; here's one of them:
Overloads Public Shared Function Show(ByVal text As String, _
ByVal caption As String, ByVal buttons As MessageBoxButtons, _

VB.NET BY PROF.A.D.CHAVAN Page 35


UNIT-II

ByVal icon As MessageBoxIcon, ByVal defaultButton As _


MessageBoxDefaultButton, ByVal options As MessageBoxOptions _)
As DialogResult
Here are the arguments you pass to this method:
 text—The text to display in the message box.
 caption—The text to display in the title bar of the message box.
 buttons—One of the MessageBoxButtons enumeration values that specifies
which buttons to display in the message box. See below.
 icon—One of the MessageBoxIcon enumeration values that specifies which
icon to display in the message box. See below.
 defaultButton—One of the MessageBoxDefaultButton enumeration values
that specifies which is the default button for the message box. See below.
 options—One of the MessageBoxOptions enumeration values that specifies
which display and association options will be used for the message box. See
below.Here are the MessageBoxButtons enumeration values:
 AbortRetryIgnore— The message box will show Abort, Retry, and Ignore
buttons.
 OK— The message box will show an OK button.
 OKCancel— The message box will show OK and Cancel buttons.
 RetryCancel— The message box will show Retry and Cancel buttons.
 YesNo— The message box will show Yes and No buttons.
 YesNoCancel— The message box will show Yes, No, and Cancel buttons.
Here are the MessageBoxIcon enumeration values:
 Asterisk— Shows an icon displaying a lowercase letter i in a circle.
 Error— Shows an icon displaying a white X in a circle with a red
background.
 Exclamation— Shows an icon displaying an exclamation point in a triangle
with a yellow background.
 Hand— Shows an icon displaying a white X in a circle with a red
background.
 Information— Shows an icon displaying a lowercase letter i in a circle.
 None— Shows no icons.
 Question— Shows an icon displaying a question mark in a circle.
 Stop— Shows an icon displaying white X in a circle with a red background.
 Warning— Shows an icon displaying an exclamation point in a triangle
with a yellow background.Here are the MessageBoxDefaultButton
enumeration values:
 Button1— Makes the first button on the message box the default button.
 Button2— Makes the second button on the message box the default button.
 Button3— Makes the third button on the message box the default button.

VB.NET BY PROF.A.D.CHAVAN Page 36


UNIT-II

Here are the MessageBoxOptions enumeration values:


 DefaultDesktopOnly— Displays the message box on the active desktop.
 RightAlign— The message box text is right-aligned.
 RtlReading— Specifies that the message box text is displayed with right to
left reading order.
The result of the Show method is a value from the DialogResult enumeration,
showing what button the user clicked:
 Abort— Returns Abort.
 Cancel— Returns Cancel.
 Ignore— Returns Ignore.
 No— Returns No.
 None— Nothing is returned from the dialog box. (Note that this means that
a modal dialog continues running.)
 OK— Returns OK.
 Retry— Returns Retry.
 Yes— Returns Yes.
Here's an example putting this to work, from the MsgAndInputBoxes. Note
that I'm testing the returned result to see if the user clicked the OK button:
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Dim Result As Integer
Result = MessageBox.Show("This is a message box!", "Message Box", _
MessageBoxButtons.OKCancel, MessageBoxIcon.Information, _
MessageBoxDefaultButton.Button1, _
MessageBoxOptions.DefaultDesktopOnly)
If (Result = DialogResult.OK) Then
TextBox1.Text = "You clicked OK"
End If
End Sub
You can see the results of this code in Figure . Note that this message box looks
just like the one created with the MsgBox function in the previous topic.

Figure : A message box created with the MessageBox class's Show method.

VB.NET BY PROF.A.D.CHAVAN Page 37


UNIT-II

 InputBox Function
You can use the InputBox function to get a string of text from the user.
Here's the syntax for this function:
Public Function InputBox(Prompt As String [, Title As _String = "" [,
DefaultResponse As String = "" [, _XPos As Integer = -1 [, YPos As Integer =
-1]]]]) As String
And here are the arguments for this function:
 Prompt— A string expression displayed as the message in the dialog box.
The maximum length is about 1,024 characters (depending on the width of
the characters used).
 Title— String expression displayed in the title bar of the dialog box. Note
that if you omit Title, the application name is placed in the title bar.
 DefaultResponse— A string expression displayed in the text box as the
default response if no other input is provided. Note that if you omit
DefaultResponse, the displayed text box is empty.
 XPos— The distance in pixels of the left edge of the dialog box from the left
edge of the screen. Note that if you omit XPos, the dialog box is centered
horizontally.
 YPos— The distance in pixels of the upper edge of the dialog box from the
top of the screen. Note that if you omit YPos, the dialog box is positioned
vertically about one-third of the way down the screen.
Input boxes let you display a prompt and read a line of text typed by the user,
and the InputBox function returns the string result. Here's an example from the
MsgAndInputBoxes.
Private Sub Button3_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button3.Click
Dim Result As String
Result = InputBox("Enter your text!")
TextBox1.Text = Result
End Sub
You can see the results of this code in below Figure .

Figure : An input box.

VB.NET BY PROF.A.D.CHAVAN Page 38


UNIT-II

When the user enters text and clicks OK, the InputBox function returns that
text, and the code displays it in the text box in the MsgAndInput example, as you
see in below Figure .

Figure : Reading text using an input box.


 String Function
String function that allows you to manipulate strings and return results
These are the following sting functions.
1. The Len Function
The length function is used to find out the number of characters in any given
string.
Syntax
Len(string)
Example
Len("Amaravati")
Length is 9
2. Asc() Function
Asc Function is used to return the character ascii code for the first character in the
string.
Syntax:
Asc( “String”)
In the above syntax, String specifies the string whose first character is used to
return the character code.
Example:
Module Module1
Sub Main()
Console.WriteLine("Character Code of B in Box is::" & Asc("Box"))
Console.WriteLine("Character Code of A in A is::" & Asc("A"))
Console.ReadLine()
End Sub
End Module
VB.NET BY PROF.A.D.CHAVAN Page 39
UNIT-II

Result:
Character Code of B in Box is:: 66
Character Code of A in A is:: 65
In the above example, the character ascii code for 'B' and 'A' are returned as '66'
and '65' respectively. Convert a string to its ASCII representation may be useful
when you're producing the code for HTML forms with hidden/visible field.
3.Chr Function
Chr Function is used to return the character for the specified Character Code(Ascii
Value).
Syntax:
Chr( CharCode)
In the above syntax CharCode specifies the Character Code based on which the
associated character is returned.
Example:
Module Module1
Sub Main()
Console.WriteLine("Character for Character Code 45 is::" & Chr("45"))
Console.WriteLine("Character for Character Code 76 is::" & Chr("76"))
Console.ReadLine()
End Sub
End Module
Result:
Character for Character Code 45 is::-
Character for Character Code 76 is::L
In the above example, the character for the the ascii value '45' and '76' are returned
as '-' and 'L' using chr convert function.
4.GetChar Function
GetChar Function is used to return the character of the string from the specified
index.
Syntax:
GetChar(“ String”, Index Value )
In the above syntax String specifies the string from which the character with the
Index value is returned.
Example:
Module Module1
Sub Main()
Dim Str As String
Str = " Welcomes You"
Console.WriteLine("Character at the index value 4 is:" & GetChar(Str, 4))
Console.ReadLine()
VB.NET BY PROF.A.D.CHAVAN Page 40
UNIT-II

End Sub
End Module
Result:
Character at the index value 4 is: c
In the above GetChar Function example, the character 'c' is at the index 4 of the
given string.
5.InStr Function
Instr String Function is used to find the starting position of a substring inside a
string.
Syntax:
InStr( Start , String1 ,String2)
In the above syntax Start specifies the starting position for the search, String1
specifies the string to search, the substring specifed as String2.
Example:
Module Module1
Sub Main()
Console.WriteLine("Starting index of HI in the stringis::" & InStr("HI THIS IS CA
CLUB", "HI"))
Console.ReadLine()
End Sub
End Module
Result:
Starting index of HI in the string is::1
In the above example, the Instr function returns 1 as the substring 'HI' is in the
begining of the string.
6. The Mid function
The mid function is used to Return a substring containing a specified number of
characters from a string.
Syntax
Mid (string, start[, length])
string - String expression from which characters are returned.
start - Long. Character position in string at which the part to be taken begins.
length - Length is Optional. Number of characters to return.
Example
Mid("Amaravati", 3, 4)
Output is rava
7. The Left Function
The Left function extract the left portion of a string.
Syntax
Left("string", n)
VB.NET BY PROF.A.D.CHAVAN Page 41
UNIT-II

Where n is the no of characters to extract


Example
Left("Amaravati", 4)
Output is Amar
8. The Right Function
The Right function extract the right portion of a string.
Syntax
Right("string", n)
Where n is the no of characters to extract
Example
Right("Amaravati", 6)
Output is ravati
9. The Space Function
The space function is used to Return a string containing the specified number of
blank spaces.
Syntax
Space (number)
Example
Spaces(“Amarpal Chavan”,4)
Output is pal Chavan
10. The Replace Function
The replace function is used to replacing some text in a string with some other text.
Syntax
Replace( string, searchtext, replacetext )
Example
Replace("Amarvati", "arv", "xxx")
Output is Amxxxati
11. The Trim function
The trim function trims the empty spaces on both side of the String.
Syntax
Trim ("String")
Example
Trim(" Amaravati ")
Output is Amaravati
12. The Ltrim Function
The Ltrim function trims the empty spaces of the left portion of the string.
Syntax
Ltrim("string")
Example
Ltrim(" Amaravati ")
VB.NET BY PROF.A.D.CHAVAN Page 42
UNIT-II

Output is Amaravati--
13. The Rtrim Function
The Rtrim function trims the empty spaces of the Right portion of the string.
Syntax
Rtrim("string")
Example
Ltrim(" Amaravati ")
Output is --Amaravati
14. The Ucase and the Lcase Functions
The Ucase function converts all the characters of a string to capital letters. On the
other hand, the Lcase function converts all the characters of a string to small
letters.
Ucase(“string”)
Lcase(“string”)
Example
Ucase(“amarvati”)
Output is AMARAVATI
Lcase(“AMAVATI”)
Output is amaravati
15. Str Function
Str() String Function is used to return string equivalent for the specified integer.
Syntax:
Str( Number )
In the above syntax Number specifies a valid numeric expression.
Example:
Module Module1
Sub Main()
Console.WriteLine('String returned for 5.5 is::' & Str(5.5))
Console.WriteLine('String returned for -5.5 is::' & Str(-5.5))
Console.ReadLine()
End Sub
End Module
Result:
String returned for 5.5 is:: 5.5
String returned for -5.5 is::-5.5
In the above example, preceding space is left for positive characters, but a minus is
displayed for negative integers. Thus Str string function can be used.
16. StrComp Function
StrComp String Function is used to compare two strings to return values '-1', '1', '0'
based on the value.
VB.NET BY PROF.A.D.CHAVAN Page 43
UNIT-II

Syntax:
StrComp (String1, String2, Optional Comparison Method)
In the above syntax, String1 and String2 specifies the two strings to compare.
The optional comparison method can have Binary or Text for text and binary
comparison.
Example:
Module Module1
Sub Main()
Dim Str1 As String = "Amaravati"
Dim Str2 As String = "amaravati"
Console.WriteLine("Result of string comparison is:: "& StrComp(Str1, Str2,
CompareMethod.Binary))
Console.ReadLine()
End Sub
End Module
Result:
Result of string comparison is:: -1
In the above example, since Str1 and Str2 are compared using a binary
method.if string1 is less than string2 then it return value is -1, if string1 is greater
than string2 then it return value is 1and if string1 is equal to string2 then it return
value is 0.Both the strings are similar except that the first character is in uppercase
in str1, so it sorts ahead to return '-1'. Thus StrComp Function can be used.
17.StrReverse Function
StrReverse Function is used to return a string with the character reversed.
Syntax:
StrReverse (“String”)
In the above syntax String is the string whose characters are reversed.
Example:
Module Module1
Sub Main()
Dim Str1 As String = "AMARAVATI"
Console.WriteLine("Reversed string is:: " & StrReverse(Str1))
Console.ReadLine()
End Sub
End Module
Result:
Reversed string is:: ITAVARAMA
In the above example, the string is reversed using the StrReverse function to
return 'ITAVARAMA'.

VB.NET BY PROF.A.D.CHAVAN Page 44


UNIT-II

18.Val Function
Val Function is used to return the numbers contained in a string as a numeric
value of appropriate type.
Syntax:
Val (Expression)
Where expression is any string, object or any numeric value
Example:
Module Module1
Sub Main()
Console.WriteLine("Value of 2 is: " & Val("1"))
Console.WriteLine("Value of 2,3 is: " & Val("2,3"))
Console.ReadLine()
End Sub
End Module
Result:
Value of 2 is: 1
Value of 2,3 is: 2
In the above example, all the number contained in string is returned, but if a
number is after a non numeric character is not returned. Thus Val string function
can be used.
19.InStrRev Function
InStrRev String Function is used return the index of the first occurence of a
substring inside a string by searching from right to left.
Syntax:
InStrRev(StringCheck , StringMatch , Optional Start, CompareMethod )
In the above syntax StringMatch specifies the string to be searched for its
first occurence inside the string StringCheck starting from right to left. Start is an
optional value to specify the starting position for the search, by default it is -1, so
the search is done from right to left, if a value is specified the search is done from
left to right. A compare method to specify the type of comparision
Example:
Module Module1
Sub Main()
Sub Main()
Console.WriteLine("Index of First Occurence of 'a' is::"& InStrRev("Visual basic
.NET", "a"))
Console.WriteLine("Index of First Occurence of 'b' is::"& InStrRev("Visual basic
.NET ", "b", 5))
Console.ReadLine()

VB.NET BY PROF.A.D.CHAVAN Page 45


UNIT-II

End Sub
End Sub
End Module
Result:
Index of First Occurence of 'a' is::9
Index of First Occurence of 'b' is::3
In the above example, the InStrRev function returns 9 as the index a since the
starting value for the start value by default is set to the end of string. But for b the
start value is set to '5' so the search is done from left to right so the index is '3'.
For Example - This example defines all the above function.
Module Module1
Sub Main()
Dim leng As String = Len(" Rohatash kumar")
Console.WriteLine("length is :" & leng)
Dim middle As String = Mid("Rohatash Kumar", 3, 4)
Console.WriteLine("Mid is :" & middle)
Dim leftf As String = Left("Rohatash Kumar", 3)
Console.WriteLine("Left is:" & leftf)
Dim rightr As String = Right("rohatash kumar", 6)
Console.WriteLine("Right is :" & rightr)
Dim spaces As String = Spaces("rohatash kumar", 7)
Console.WriteLine("Space is :" & spaces)
Dim replaces As String = Replace("rohatash kumar", "hat", "nmo")
Console.WriteLine("Replace is :" & replaces)
Dim trimt As String = Trim(" rohatash kumar ")
Console.WriteLine("Trim is :" & trimt)
Dim ltriml As String = LTrim(" rohatash kumar ")
Console.WriteLine("ltrim is :" & ltriml)
Dim rtrimr As String = RTrim(" rohatash kumar ")
Console.WriteLine("rtrim is :" & rtrimr)
Dim ucaseu As String = UCase("rohatash kumar")
Console.WriteLine("Ucase is :" & ucaseu)
Dim lcasel As String = LCase("ROHATASH KUMAR")
Console.WriteLine("Ucase is :" & lcasel)
End Sub
End Module
Now run the console application.

VB.NET BY PROF.A.D.CHAVAN Page 46


UNIT-II

 Math functions
Math functions are very useful function when we need to perform
mathematical operations such as some trigonometric and logarithmtics. To use
these math functions without qualification, import the System.Math namespace.
1. Abs() Function
The Abs Function is used to returns the absolute value of a specified number.
Syntax
Math.Abs(n)
Here, n is the number.
This function returns the absolute value.
2. Min() Function
The Min function is used to find out the minimum value from two number.
Syntax
Math.Min(n1, n2)
Here, n1 and n2 are the two number.
This function returns the min value from n1 and n2.
3. Max() Function
The Min function is used to find out the maximum value from two number.
Syntax
Math.Min(n1, n2)
Here, n1 and n2 are the two number.
This function returns the maximum value from n1 and n2.
4. Sqrt() Function
The pow function is used to returns the square root of the number.
Syntax
Math.Sqrt(n1)
Here, n1 is the number.

VB.NET BY PROF.A.D.CHAVAN Page 47


UNIT-II

This function returns the maximum value from n1 and n2.


This function returns a Double value specifying the square root of a number.
5. Pow() Function
This function is used to Returns a specified number raised to the specified power.
Syntax
Math.Pow(n1, n2 )
Here, n1 is the number and n2 is the power of the number.
6. Sin() Function
This function is used to Returns the sine of the specified angle.
Syntax
Math.Sin(90)
Here, 90 is the angle.
7. Log() Function
This function is used to find the logarithm of a specified number.
Syntax
Math.log(n1)
Here, n1 is the number.
For example
The below example describe all the above function.
Module Module1
Sub Main()
Dim absolute As Integer
absolute = Math.Abs(-16)
Console.WriteLine("The absolute value is: " & absolute)
Dim minimum As Integer
minimum = Math.Min(18, 12)
Console.WriteLine("The minimum value is: " & minimum)
Dim maximum As Integer
maximum = Math.Max(18, 12)
Console.WriteLine("The maximum value is: " & maximum)
Dim square As Integer
square = Math.Sqrt(9)
Console.WriteLine("The square root is: " & square)
Dim power As Integer
power = Math.Pow(2, 3)
Console.WriteLine("The power is: " & power)
Dim sine As Integer
sine = Math.Sin(90)
Console.WriteLine("sine value of 90: " & sine)
Dim logvalue As Integer
VB.NET BY PROF.A.D.CHAVAN Page 48
UNIT-II

logvalue = Math.Log(15)
Console.WriteLine("log value of 16 is: " & logvalue)
End Sub
End Module
OUTPUT

 Date and Time Functions


Date and time unction can be used to manipulate function and return the
specific result
1.DateAdd Function
DateAdd Function is used to returns a date with a date,time value added with a
specified time intreval.
Syntax:
DateAdd(interval, number, date)
Example:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs)Handles MyBase.Load
MsgBox("10 Days after the current date is::"
& DateAdd(DateInterval.Day, 10, Now))
End Sub
End Class
In the above DateAdd Function example, a date is added after an intreval of 10
days to the current date value.
2. DateDiff Function
DateDiff Function is used to return a long value specifying the number of time
intrevals between the specified date values.
Syntax:
DateAdd(interval,date1,date2)

VB.NET BY PROF.A.D.CHAVAN Page 49


UNIT-II

Example:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
Dim d1 As Date = #2/4/2009#
Dim d2 As Date = #2/4/2010#
Dim res As Long
res = DateDiff(DateInterval.Day, d1, d2)
MsgBox("The number of time intrevals between the dates is::" & res)
End Sub
End Class
In the above DateDiff Function example, the time intrevals between two same
dates of different years are found using the 'DateDiff()'. The function returns '365'.
3.DatePart Function
DatePart Function is returns an integer value containing the specified component
of the Date value.
Syntax:
DatePart (interval, date)
Example:
Module Module1
Sub Main()
Console.WriteLine("The date part of '01/10/2010' is::"& DatePart("d",
"01/10/2010"))
Console.ReadLine()
End Sub
End Module
Result:
The date part of '01/10/2010' is:: 10
In the above DatePart Function example, the date value entered is in the
mm:dd:yy format, so the date returned is 10.
4.DateSerial Function
DateSerial Function is returns an date value for the specified year, month and
day with the time set to the midnight. If the month value is '0' or '-1' the month
December or november of the previous year is taken. If the month value is '1',
january month of the calculated year is taken, if '13' january of the following year
is taken. If the Day value is '1' refers to the first day of the calculated month, '0' for
the last day of previous month, '-1' the penultimate day of the previous month.
Syntax:
DateSerial(Year,Month,Day)

VB.NET BY PROF.A.D.CHAVAN Page 50


UNIT-II

Example:
Module Module1
Sub Main()
Dim a As Date
a = DateSerial(2010, 2, 21)
Console.WriteLine(a)
Console.ReadLine()
End Sub
End Module
Result:
2/21/2010 12:00:00 AM
In the above DateSerial Function example, the date value entered is displayed with
the time set to the midnight using the DateSerial().
5.DateValue Function
DateValue Function is returns an date value containing the date information as a
string, with the time set to the midnight.
Syntax:
DateValue(Date)
Example:
Module Module1
Sub Main()
Console.WriteLine("Date information as a String is::"& DateValue("5/10/2010
12:00:01 AM"))
Console.ReadLine()
End Sub
End Module
Result:
5/10/2010
In the above DateValue Function example, the date information alone is displayed
as a String using the DateValue function.
6.Day Function
Day Function is returns the day of the month from the Date value passed as an
Integer.
Syntax:
Day(Date)
Example:
Module Module1
Sub Main()
Console.WriteLine("Day value for the current date is::" & Day(Now))
Console.ReadLine()
VB.NET BY PROF.A.D.CHAVAN Page 51
UNIT-II

End Sub
End Module
Result:
22
In the above Day Function example, the date information is passed as an argument,
so that the day value alone is returned.
7.IsDate Function
IsDate Function is checks if the given expression is a valid date and returns a
boolean true or false.
Syntax:
IsDate(Expession)
Example:
Module Module1
Sub Main()
Dim curdat As Date
curdat = "5/31/2010"
Console.WriteLine("Is '5/31/2010' a valid date::"& IsDate(curdat))
Console.ReadLine()
End Sub
End Module
Result:
Is '5/31/2010' a valid date:: True
In the above example, the date given as the argument is valid, the IsDate function
returns True.
8.Month Function
Month Function is returns the month of the year as an integer value in the range
of 1-12.
Syntax:
Month(Date)
Example:
Module Module1
Sub Main()
Dim dat As Date
dat = "6/23/2010"
Console.WriteLine("Month value of the given date
is::" & Month(dat))
Console.ReadLine()
End Sub
End Module

VB.NET BY PROF.A.D.CHAVAN Page 52


UNIT-II

Result:
Month value of the given date is:: 6
In the above example, the month for the given date is returned using the Month
function.
9.MonthName Function
This Function is returns a string containing the name of the specified month.
Syntax:
MonthName(Month, Abbreviates)
In the above example, 'month' is represented as an integer value, the 'Abbreviates'
is an optional argument which is represented as boolean.
Example:
Module Module1
Sub Main()
Console.WriteLine("Name of the month is:: " & MonthName(12))
Console.WriteLine("Abbreviated name of month is::"& MonthName(12, True))
Console.ReadLine()
End Sub
End Module
Result:
Name of the month is:: December
Abbreviated name of month is:: Dec
In the above monthname function example, the first the name of the month is
displayed completly. Then optional abbreviation is is set to true to display the
abbreviated name of the month.
10. WeekDay Function
Weekday Date Function is returns an integer value for the day of the week in the
range 1 to 7, with '1' representing Sunday.
Syntax:
Weekday(Date)
Example:
Module Module1
Sub Main()
Console.WriteLine("Day of the Week(1-7)::"& Weekday(Now))
Console.ReadLine()
End Sub
End Module
In the above example, the day value is displayed using the weekday date function
in the range 1-7 based on current date specified using Now.

VB.NET BY PROF.A.D.CHAVAN Page 53


UNIT-II

11.WeekdayName Function
WeekdayName Date Function is accepts a day of the week as integer, to return a
string representing the name of day of the week. Usually this function is used with
the Weekday function.
Syntax:
WeekdayName(Date)
Example:
Module Module1
Sub Main()
Console.WriteLine("Weekday for the date '05/22/2010'is::" &
WeekdayName(Weekday("5/22/2010")))
Console.ReadLine()
End Sub
End Module
In the above example, the day value is got using the Weekday date function, then
the weekday name is returned using the Weekday Name function represented as a
string.
12.Hour Function
Hour Function is returns an integer value in the range 0 to 23 that represents the
hour.
Syntax:
Hour(Expression)
Example:
Module Module1
Sub Main()
Console.WriteLine("Current hour as integer from 0-23 is:: " & Hour(Now))
Console.ReadLine()
End Sub
End Module
In the above Hour Function example, the current hour is represented in an integer
value.
13.Minute Function
Minute Function is returns an integer value in the range 0 to 59, that represents the
minute of the hour.
Syntax:
Minute(Expression)
Example:
Module Module1
Sub Main()
Console.WriteLine("Current minute of the hour is :: " & Minute(Now))
VB.NET BY PROF.A.D.CHAVAN Page 54
UNIT-II

Console.ReadLine()
End Sub
End Module
In the above example, the current minute of the hour is represented in an integer
value using minute function
14.Second Function
Second() Time Function is returns an integer value between 0 to 59, that represents
the second of the current minute.
Syntax:
Second(Expression)
Example:
Module Module1
Sub Main()
Console.WriteLine("Current second of the minute is:: " & Second(Now))
Console.ReadLine()
End Sub
End Module
In the above example, the current second of the minute is represented in an integer
value by using this time function.
15.Timeserial Function
TimeSerial Time Function is returns an date value with the specified hour, minute,
second with the date information is set to January 1 of year 1.
Syntax:
Timeserial(hour, minute, second)
Example:
Module Module1
Sub Main()
Console.WriteLine("Time displayed using Timeserial() is:: "& TimeSerial(4, 30,
23))
Console.ReadLine()
End Sub
End Module
Result:
Time displayed using Timeserial() is :: 4:30:23 AM
In the above example, the time is displayed by specifying the hour, minute,
seconds using the Timeserial time function.

VB.NET BY PROF.A.D.CHAVAN Page 55

You might also like