Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit - 2 Part B

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

Unit – 2

Introduction to Visual Basic .Net IDE

Object Browser:

The Object Browser allows you to browse through all available objects in your project and see
their properties, methods and events. In addition, you can see the procedures and constants that
are available from object libraries in your project. You can easily display online Help as you
browse. You can use the Object Browser to find and use objects that you create, as well as
objects from other applications.

You can get help for the Object Browser by searching for Object Browser in Help.

To navigate the Object Browser

1. Activate a module.

2. From the View menu, choose Object Browser (F2), or use the toolbar shortcut: .
3. Select the name of the project or library that you want to view in the Project/Library list.
4. Use the Class list to select the class; use the Member list to select specific members of your
class or project.
5. View information about the class or member you selected in the Details section at the
bottom of the window.
6. Use the Help button to display the Help topic for the class or member you selected.

Difference between VB.NET and Visual Basic

VB.NET

VB.NET is also known as Visual Basic.NET. It stands for Visual Basic .Network Enabled
Technologies. It is a simple, high-level, object-oriented programming language developed
by Microsoft in 2002. It is a successor of Visual Basic 6.0, which is implemented on the
Microsoft .NET Framework. With this language, you can develop a fully object-oriented
application that is similar to an application created through another language such as C++,
Java, or C#.

Feature of VB.NET

1. Inheritance (object-oriented language)


2. Delegates and events
3. Parameterized constructors
4. Method overloading/overriding
5. Type-safe

Visual Basic

Ms. Chitra Nasa Page 1


Unit – 2

Visual Basic (VB) is a programming language developed by Microsoft in 1992. The purpose
of this language is to develop an application that can run on different versions of the
Windows operating system. A Visual Basic evolved from Basic Language; Basic language is
easier to read than other languages. The final version of Visual Basic was released in 1998.
Microsoft then launched a Visual Basic DotNet ('VB.NET') language, which is much better
than Visual Basic in all aspects such as performance, reliability, working environment, easy
to build, and debugging an application.

Features of Visual Basic

1. User Interface design


2. Rapid Application Development
3. Using this language, you can use internet or intranet services in your application.
4. It has powerful database access tools, by which you can easily develop front end
applications.
5. It also supports ActiveX technology, in which you can access the features of other
application in system application. For example: Microsoft Word, Microsoft Excel, etc.

Difference Between VB. NET and Visual Basic


VB .NET Visual Basic

It stands for Visual Basic. Network It is a programming language


Enables Technology. It is also developed by Microsoft for
developed by Microsoft, and this the fastest development of a
language was based on the .Net window-based operating
Framework. Furthermore, it is specially system as well as applications.
designed for VB developers.

It is a modern, fully object-oriented VB is the predecessor of


language that replaced VB6. VB.NET and was not an
object-oriented language. So,
it is not actively maintained.

A VB.NET uses the Common Visual Basic uses the VB-


Language Runtime (CLR) component Runtime environment.
of .Net Framework at runtime. It has
better features and design
implementation as compared to VB-
Runtime.

It is a compiled language It is an Interpreter based


language

Ms. Chitra Nasa Page 2


Unit – 2

It does not support backward It supports backward


compatibility. compatibility.

It is a type-safe language. It is not a type-safe language.

In VB.NET, data is handled using the Data Connectivity and


ADO.net protocol. handling are done through
DAO, RDO, and ADO
(ActiveX Data Object)
protocol,

Object does not support default The Object support default


property. property of virtual basic.

In the VB.Net parameter are passed by In VB, most of the parameters


a default value. are passed by reference.

A Multithreaded application can be It does not support the


developed in VB.NET. multithread concept.

Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in VB.Net has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations
that can be applied to the variable.
We have already discussed various data types. The basic value types provided in VB.Net can be
categorized as −

Type Example

Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long,


ULong and Char

Floating point types Single and Double

Decimal types Decimal

Ms. Chitra Nasa Page 3


Unit – 2

Boolean types True or False values, as assigned

Date types Date

VB.Net also allows defining other value types of variable like Enum and reference types of
variables like Class. We will discuss date types and Classes in subsequent chapters.
Variable Declaration in VB.Net
The Dim statement is used for variable declaration and storage allocation for one or more
variables. The Dim statement is used at module, class, structure, procedure or block level.
Syntax for variable declaration in VB.Net is −
[ < attributelist > ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]
[ ReadOnly ] Dim [ WithEvents ] variablelist
Where,
 attributelist is a list of attributes that apply to the variable. Optional.
 accessmodifier defines the access levels of the variables, it has values as - Public,
Protected, Friend, Protected Friend and Private. Optional.
 Shared declares a shared variable, which is not associated with any specific instance of a
class or structure, rather available to all the instances of the class or structure. Optional.
 Shadows indicate that the variable re-declares and hides an identically named element, or
set of overloaded elements, in a base class. Optional.
 Static indicates that the variable will retain its value, even when the after termination of
the procedure in which it is declared. Optional.
 ReadOnly means the variable can be read, but not written. Optional.
 WithEvents specifies that the variable is used to respond to events raised by the instance
assigned to the variable. Optional.
 Variablelist provides the list of variables declared.
Each variable in the variable list has the following syntax and parts −
variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]
Where,
 variablename − is the name of the variable
 boundslist − optional. It provides list of bounds of each dimension of an array variable.
 New − optional. It creates a new instance of the class when the Dim statement runs.
 datatype − Required if Option Strict is On. It specifies the data type of the variable.

Ms. Chitra Nasa Page 4


Unit – 2

 initializer − Optional if New is not specified. Expression that is evaluated and assigned
to the variable when it is created.
Some valid variable declarations along with their definition are shown here −
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

Variable Initialization in VB.Net


Variables are initialized (assigned a value) with an equal sign followed by a constant
expression. The general form of initialization is −
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
You can initialize a variable at the time of declaration as follows −
Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"

Example
Try the following example which makes use of various types of variables −
Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double

a = 10
b = 20
c=a+b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module

Ms. Chitra Nasa Page 5


Unit – 2

What are Data Types?

Data types determine the type of data that any variable can store. Variables belonging to different
data types are allocated different amounts of space in the memory. There are various data types
in VB.NET. They include:

 Boolean: the allocated storage depends on the platform of implementation. Its value can
be either True or False.
 Byte: allocated storage space of 1 byte. Values range from 0 to 255 (unsigned).
 Char: allocated a space of 2 bytes. Values range from 0 to 65535 (unsigned).
 Date: allocated storage space of 8 bytes. Values range from 0:00:00 (midnight) January
1, 0001 to 11:59:59 PM of December 31, 9999.
 Integer: has a storage space of 4 bytes. Values range between -2,147,483,648 to
2,147,483,647 (signed).
 Long: has a storage space of 8 bytes. Numbers range from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807(signed).
 String: The storage space allocated depends on the platform of implementation. Values
range from 0 to about 2 billion Unicode characters.

Type Conversion Functions

There are functions that we can use to convert from one data type to another. They include:

 CBool (expression): converts the expression to a Boolean data type.


 CDate(expression): converts the expression to a Date data type.
 CDbl(expression): converts the expression to a Double data type.
 CByte (expression): converts the expression to a byte data type.
 CChar(expression): converts the expression to a Char data type.
 CLng(expression): converts the expression to a Long data type.
 CDec(expression): converts the expression to a Decimal data type.
 CInt(expression): converts the expression to an Integer data type.
 CObj(expression): converts the expression to an Object data type.
 CStr(expression): converts the expression to a String data type.
 CSByte(expression): converts the expression to a Byte data type.
 CShort(expression): converts the expression to a Short data type.

Variable Declaration

In VB.NET, the declaration of a variable involves giving the variable a name and defining the
data type to which it belongs. We use the following syntax:

Dim Variable_Name as Data_Type

In the above syntax, Variable_Name is the variable name while Data_Type is the name to which
the variable belongs.

Ms. Chitra Nasa Page 6


Unit – 2

Here is an example of a valid variable declaration in VB.NET:

Dim x As Integer

In the above example, 'x' is the variable name while Integer is the data type to which variable x
belongs.

Variable Initialization

Initializing a variable means assigning a value to the variable. The following example
demonstrates this:

Dim x As Integer
x = 10

Above, we have declared an integer variable named 'x' and assigned it a value of 10. Here is
another example:

Dim name As String


name = "John"

Above, we have declared a string variable name and assigned it a value of John.

If you declare a Boolean variable, its value must be either True or false. For example:

Dim checker As Boolean


checker = True

Array
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,

Ms. Chitra Nasa Page 7


Unit – 2

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 −
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

Ms. Chitra Nasa Page 8


Unit – 2

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()
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

Ms. Chitra Nasa Page 9


Unit – 2

9 0
10 0
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 −
Live Demo

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
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

Array List

Ms. Chitra Nasa Page 10


Unit – 2

It represents an ordered collection of an object that can be indexed individually. It is basically


an alternative to an array. However, unlike array, you can add and remove items from a list at a
specified position using an index and the array resizes itself automatically. It also allows
dynamic memory allocation, adding, searching and sorting items in the list.
Properties and Methods of the ArrayList Class
The following table lists some of the commonly used properties of the ArrayList class −

Sr.No. Property & Description

1
Capacity
Gets or sets the number of elements that the ArrayList can contain.

2
Count
Gets the number of elements actually contained in the ArrayList.

3
IsFixedSize
Gets a value indicating whether the ArrayList has a fixed size.

4
IsReadOnly
Gets a value indicating whether the ArrayList is read-only.

5
Item
Gets or sets the element at the specified index.

Sub Main()
Dim al As ArrayList = New ArrayList()
Dim i As Integer
Console.WriteLine("Adding some numbers:")
al.Add(45)
al.Add(78)
al.Add(33)
al.Add(56)
al.Add(12)
al.Add(23)
al.Add(9)
Console.WriteLine("Capacity: {0} ", al.Capacity)
Console.WriteLine("Count: {0}", al.Count)
Console.Write("Content: ")

Ms. Chitra Nasa Page 11


Unit – 2

For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.Write("Sorted Content: ")
al.Sort()

For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Adding some numbers:
Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78

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:

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.

Enum Temperature

Ms. Chitra Nasa Page 12


Unit – 2

Low
Medium
High
End Enum

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:

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.

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.

Dim value As Temperature = Temperature.Medium


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

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

Ms. Chitra Nasa Page 13


Unit – 2

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.

Constant
The constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified
after their definition.

Ms. Chitra Nasa Page 14


Unit – 2

An enumeration is a set of named integer constants.


Declaring Constants
In VB.Net, constants are declared using the Const statement. The Const statement is used at
module, class, structure, procedure, or block level for use in place of literal values.
The syntax for the Const statement is −
[ < attributelist > ] [ accessmodifier ] [ Shadows ]
Const constantlist
Where,
 attributelist − specifies the list of attributes applied to the constants; you can provide
multiple attributes separated by commas. Optional.
 accessmodifier − specifies which code can access these constants. Optional. Values can
be either of the: Public, Protected, Friend, Protected Friend, or Private.
 Shadows − this makes the constant hide a programming element of identical name in a
base class. Optional.
 Constantlist − gives the list of names of constants declared. Required.
Where, each constant name has the following syntax and parts −
constantname [ As datatype ] = initializer
 constantname − specifies the name of the constant
 datatype − specifies the data type of the constant
 initializer − specifies the value assigned to the constant
For example,
'The following statements declare constants.'
Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415

Example
The following example demonstrates declaration and use of a constant value −
Live Demo

Module constantsNenum
Sub Main()
Const PI = 3.14149
Dim radius, area As Single
radius = 7
area = PI * radius * radius

Ms. Chitra Nasa Page 15


Unit – 2

Console.WriteLine("Area = " & Str(area))


Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Area = 153.933

Structures

You begin a structure declaration with the Structure Statement, and you end it with the End
Structure statement. Between these two statements you must declare at least one element. The
elements can be of any data type, but at least one must be either a nonshared variable or a
nonshared, noncustom event.

You cannot initialize any of the structure elements in the structure declaration. When you declare
a variable to be of a structure type, you assign values to the elements by accessing them through
the variable.

Private Structure employee


Public givenName As String
Public familyName As String
Public phoneExtension As Long
Private salary As Decimal
Public Sub giveRaise(raise As Double)
salary *= raise
End Sub
Public Event salaryReviewTime()
End Structure

The salary field in the preceding example is Private, which means it is inaccessible outside the
structure, even from the containing class. However, the giveRaise procedure is Public, so it can
be called from outside the structure. Similarly, you can raise the salaryReviewTime event from
outside the structure.

Structures

A structure is a user-defined data type. Structures provide us with a way of packaging data of
different types together. A structure is declared using the structure keyword. Example to create a
structure in VB.NET:

Step 1) Create a new console application.

Step 2) Add the following code:

Ms. Chitra Nasa Page 16


Unit – 2

Module Module1
Structure Struct
Public x As Integer
Public y As Integer
End Structure
Sub Main()
Dim st As New Struct
st.x = 10
st.y = 20
Dim sum As Integer = st.x + st.y
Console.WriteLine("The result is {0}", sum)
Console.ReadKey()

End Sub
End Module

Step 3) Run the code by clicking the Start button from the toolbar. You should get the following
window:

We have used the following code:

Explanation of Code:

1. Creating a module named Module1.


2. Creating a structure named Struct.
3. Creating a variable x of type integer. Its access level has been set to Public to make it
publicly accessible.
4. Creating a variable y of type integer. Its access level has been set to Public to make it
publicly accessible.
5. End of the structure.
6. Creating the main sub-procedure.
7. Creating an object named st of type Struct. This means that it will be capable of accessing
all the properties defined within the structure named Struct.
8. Accessing the variable x defined within the structure Struct and initializing its value to
10.
9. Accessing the variable y defined within the structure Struct and initializing its value to
20.
10. Defining the variable sum and initializing its value to the sum of the values of the above
two variables.
11. Printing some text and the result of the above operation on the console.
12. Pausing the console window waiting for a user to take action to close it.

Ms. Chitra Nasa Page 17


Unit – 2

13. End of the main sub-procedure.


14. End of the module.

Procedure
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 so far in these
tutorials. 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 −
Live Demo

Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
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

Ms. Chitra Nasa Page 18


Unit – 2

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
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

Ms. Chitra Nasa Page 19


Unit – 2

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

The scope of a declared element is the set of all code that can refer to it without qualifying its
name or making it available through an Imports Statement (.NET Namespace and Type). An
element can have scope at one of the following levels:

S CO PE IN VISUAL B AS I C
Level Description
Block scope Available only within the code block in which
it is declared
Procedure Available to all code within the procedure in
scope which it is declared
Module scope Available to all code within the module, class,
or structure in which it is declared

Ms. Chitra Nasa Page 20


Unit – 2

S CO PE IN VISUAL B AS I C
Level Description
Namespace Available to all code in the namespace in which
scope it is declared

These levels of scope progress from the narrowest (block) to the widest (namespace),
where narrowest scope means the smallest set of code that can refer to the element without
qualification.

An If statement can be followed by an optional Else statement, which executes when the
Boolean expression is false.
Syntax
The syntax of an If...Then... Else statement in VB.Net is as follows −
If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If
If the Boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram

Example
Module decisions
Sub Main()

Ms. Chitra Nasa Page 21


Unit – 2

'local variable definition '


Dim a As Integer = 100

' 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
The If...Else If...Else Statement
An If statement can be followed by an optional Else if...Else statement, which is very useful to
test various conditions using single If...Else If statement.
When using If... Else If... Else statements, there are few points to keep in mind.
 An If can have zero or one Else's and it must come after an Else If's.
 An If can have zero to many Else If's and they must come before the Else.
 Once an Else if succeeds, none of the remaining Else If's or Else's will be tested.
Syntax
The syntax of an if...else if...else statement in VB.Net is as follows −
If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the boolean expression 3 is true
Else
' executes when the none of the above condition is true
End If
Example
Module decisions
Sub Main()

Ms. Chitra Nasa Page 22


Unit – 2

'local variable definition '


Dim a As Integer = 100
' check the boolean condition '
If (a = 10) Then
' if condition is true then print the following '
Console.WriteLine("Value of a is 10") '
ElseIf (a = 20) Then
'if else if condition is true '
Console.WriteLine("Value of a is 20") '
ElseIf (a = 30) Then
'if else if condition is true
Console.WriteLine("Value of a is 30")
Else
'if none of the conditions is true
Console.WriteLine("None of the values is matching")
End If
Console.WriteLine("Exact 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 −
None of the values is matching
Exact value of a is: 100

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.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

Ms. Chitra Nasa Page 23


Unit – 2

VB.Net provides following types of loops to handle looping requirements. Click the following
links to check their details.

Loop Type Description

Do Loop It repeats the enclosed block of statements while a


Boolean condition is True or until the condition
becomes True. It could be terminated at any time
with the Exit Do statement.

For...Next It repeats a group of statements a specified number


of times and a loop index counts the number of loop
iterations as the loop executes.

It repeats a group of statements for each element in a


For Each...Next
collection. This loop is used for accessing and
manipulating all elements in an array or a VB.Net
collection.

While... End While It executes a series of statements as long as a given


condition is True.

Ms. Chitra Nasa Page 24


Unit – 2

With... End With It is not exactly a looping construct. It executes a


series of statements that repeatedly refer to a single
object or structure.

Nested loops You can use one or more loops inside any another
While, For or Do loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
VB.Net provides the following control statements. Click the following links to check their
details.

Control Statement Description

Exit statement Terminates the loop or select case statement and


transfers execution to the statement immediately
following the loop or select case.

Continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.

GoTo statement Transfers control to the labeled statement. Though it


is not advised to use GoTo statement in your
program.

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.
Following is the general form of a typical decision making structure found in most of the
programming languages −

Ms. Chitra Nasa Page 25


Unit – 2

VB.Net provides the following types of decision making statements. Click the following links
to check their details.

Statement Description

If ... Then statement An If...Then statement consists of a


boolean expression followed by one or
more statements.

If...Then...Else statement An If...Then statement can be followed


by an optional Else statement, which
executes when the boolean expression is
false.

You can use one If or Else if statement


nested If statements
inside another If or Else if statement(s).

Select Case statement A Select Case statement allows a variable


to be tested for equality against a list of
values.

nested Select Case statements You can use one select case statement
inside another select case statement(s).

Ms. Chitra Nasa Page 26


Unit – 2

MsgBox ( ) Function

The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a
command button before he /she can continues. This format is as follows:

yourMsg=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, will display the message in the message box. The Style Value will
determine what type of command buttons appear on the message box, please refer to Table 12.1
for types of command button displayed. The Title argument will display the title of the message
board.

Table 12.1: Style Values

Style
Named Constant Buttons Displayed
Value

0 vbOkOnly Ok button

1 vbOkCancel Ok and Cancel buttons

2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.

3 vbYesNoCancel Yes, No and Cancel buttons

4 vbYesNo Yes and No buttons

5 vbRetryCancel Retry and Cancel buttons

We can use named constants in place of integers for the second argument to make the programs
more readable. In fact, Visual Basic 2012 will automatically shows up a list of named constants
where you can select one of them.

For example:

yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")

and

yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")

are the same.

Ms. Chitra Nasa Page 27


Unit – 2

yourMsg is a variable that holds values that are returned by the MsgBox ( ) function. The values
are determined by the type of buttons being clicked by the users. It has to be declared as Integer
data type in the procedure or in the general declaration section. Table 12.2 shows the values, the
corresponding named constant and buttons.

Table 12.2 : Return Values and Command Buttons

Value Named Constant Button Clicked

1 vbOk Ok button

2 vbCancel Cancel button

3 vbAbort Abort button

4 vbRetry Retry button

5 vbIgnore Ignore button

6 vbYes Yes button

7 vbNo No button

Example 12.1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
MessageBox.Show("You have clicked the OK button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub

To make the message box looks more sophisticated, you can add an icon besides the message.
There are four types of icons available in VB2012 as shown in Table 12.3

Table 12.3 Types of Icons


Value Named Constant Icon

Ms. Chitra Nasa Page 28


Unit – 2

16 vbCritical

3 vbQuestion

48 vbExclamation

64 vbInformation
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim testMsg As Integer
testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test
Message")
If testMsg = 6 Then
MessageBox.Show("You have clicked the yes button")
ElseIf testMsg = 7 Then
MessageBox.Show("You have clicked the NO button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub

The first argument, Prompt, will display the message

Figure 12.1 The MessageBox

The InputBox( ) Function

An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text.
In VB2005, you can use the following format:

myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)

myMessage is a variant data type but typically it is declared as string, which accept the message input by the users.
The arguments are explained as follows:

Ms. Chitra Nasa Page 29


Unit – 2
Prompt - the message displayed normally as a question asked.

Title - The title of the Input Box.

default-text - The default text that appears in the input field where users can use it as his intended input or he may
change to the message he wish to enter.

x-position and y-position - the position or tthe coordinates of the input box.

However, the format won't work in Visual Basic 2012 because InputBox is considered a namespace. So, you need to
key in the full reference to the Inputbox namespace, which is

Microsoft.VisualBasic.InputBox(Prompt, Title, default_text, x-position, y-position)

The parameters remain the same.

Example 12.3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Dim userMsg As String
userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message
Entry Form", "Enter your messge here", 500, 700)
If userMsg <> "" Then
MessageBox.Show(userMsg)
Else
MessageBox.Show("No Message")
End If
End Sub

The inputbox will appear as shown in the figure below when you press the command button

Ms. Chitra Nasa Page 30

You might also like