Unit - 2 Part B
Unit - 2 Part B
Unit - 2 Part B
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.
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.
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
Visual Basic
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.
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
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.
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
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
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.
There are functions that we can use to convert from one data type to another. They include:
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:
In the above syntax, Variable_Name is the variable name while Data_Type is the name to which
the variable belongs.
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:
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:
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.
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
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
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
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
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: ")
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
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
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.
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.
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.
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
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.
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:
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:
Explanation of Code:
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
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
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
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()
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 −
VB.Net provides following types of loops to handle looping requirements. Click the following
links to check their details.
Nested loops You can use one or more loops inside any another
While, For or Do loop.
Continue statement Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
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 −
VB.Net provides the following types of decision making statements. Click the following links
to check their details.
Statement Description
nested Select Case statements You can use one select case statement
inside another select case statement(s).
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:
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.
Style
Named Constant Buttons Displayed
Value
0 vbOkOnly Ok button
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:
and
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.
1 vbOk Ok 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
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
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 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:
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
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