Chapter One
Chapter One
Step
At A
Time
VB.NET HANDOUT
Detailed Lesson notes with practical exercises and applications in VB.NET Programming
Table of Contents
OBJECTIVES ....................................................................................................................................... 4
PART 1 – GENERAL INTRODUCTION AND CONSOLE PROGRAMMING........................... 4
1. ..................................................................................................................... INTRODUCTION
................................................................................................................................................................ 4
1.1. What is VB.NET ? .................................................................................................................. 4
1
1.8 Visual Basic Data Types ............................................................................................................... 24
1.8.1 Type Conversion Functions ...................................................................................................... 25
1.15 Arrays........................................................................................................................................... 43
1.15.1 Creating Arrays in VB.Net ...................................................................................................... 43
2
1.16 Functions and Subs Procedures ................................................................................................. 45
1.16.1 Sub Procedures....................................................................................................................... 46
3
PREREQUISITES
- Be able to write an Algorithm
- Understand basic programming syntaxes
OBJECTIVES
At the end of this lesson, you should be able to:
1. INTRODUCTION
1.1. What is VB.NET ?
VB.Net is a simple, modern, object-oriented computer programming language developed by
Microsoft to combine the power of .NET Framework and the common language runtime. With the
word “Basic” being in the name of the language, you can already see that this is a language for
beginners. VB.NET has the ability to create very powerful and sophisticated applications. VB.NET is a
great place to start because of how easy and straight forward it is. The syntax is easy and you will not
find yourself writing hundreds of lines of code as there are many shortcuts that make coding so much
easier in this language.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts.
Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long, String,
Boolean, etc.) and user-defined types, events, and even assemblies. All objects inherit from the base
class Object.
4
1.1.1 History of VB.NET
VB.NET is a multi-paradigm programming language
developed by Microsoft on the .NET framework. It was
launched in 2002 as a successor to the Visual Basic
language. This was the first version of VB.NET (VB.NET
7.0) and it relied on .NET version 1.0.
5
1.1.2 VB.NET Features
VB.NET comes loaded with numerous features that have made it a popular programming
language amongst programmers worldwide. These features include the following:
VB.NET is not case sensitive like other languages such as C++ and Java.
It is an object-oriented programming language. It treats everything as an object.
Automatic code formatting, XML designer, improved object browser etc.
Garbage collection is automated.
Support for Boolean conditions for decision making.
Simple multithreading, allowing your apps to deal with multiple tasks simultaneously.
Simple generics.
A standard library.
Events management.
References. You should reference an external object that is to be used in a VB.NET
application.
Attributes, which are tags for providing additional information regarding elements that
have been defined within a program.
Windows Forms- you can inherit your form from an already existing form.
6
VB.NET cannot handle pointers directly. This is a significant disadvantage since
pointers are much necessary for programming. Any additional coding will lead to many
CPU cycles, requiring more processing time. Your application will become slow.
VB.NET is easy to learn. This has led to a large talent pool. Hence, it may be
challenging to secure a job as a VB.NET programmer.
1.1.5 Summary:
VB.NET was developed by Microsoft.
It is an object-oriented language.
The language is not case sensitive.
VB.NET programs run on the .NET framework.
In VB.NET, the garbage collection process has been automated.
The language provides windows forms from which you can inherit your own forms.
VB.NET allows you to enjoy the drag and drop feature when creating a user interface.
Like any other IDE, it includes a code editor that supports syntax highlighting and code
completion using IntelliSense for variables, functions, methods, loops, and LINQ queries.
IntelliSense is supported for the included languages, as well as for XML, Cascading Style
7
Sheets, and JavaScript when developing web sites and web applications. Autocomplete
suggestions appear in a modeless list box over the code editor window, in proximity of the
editing cursor. In Visual Studio 2008 onwards, it can be made temporarily semi-transparent to
see the code obstructed by it. The code editor is used for all supported languages.
Explanation of Code:
1. This is called the namespace declaration. What we are doing is that we are including a
namespace with the name System into our programming structure. After that, we will
be able to access all the methods that have been defined in that namespace without
getting an error.
2. This is called a module declaration. Here, we have declared a module named
Module1. VB.NET is an object-oriented language. Hence we must have a class
module in every program. It is inside this module that you will be able to define the
data and methods to be used by your program.
3. This is a comment. To mark it as a comment, we added a single quote (') to the
beginning of the sentence. The VB.NET compiler will not process this part. The
purpose of comments is to improve the readability of the code. Use them to explain
the meaning of various statements in your code. Anyone reading through your code
will find it easy to understand.
4. A VB.NET module or class can have more than one procedures. It is inside
procedures where you should define your executable code. This means that the
procedure will define the class behavior. A procedure can be a Function, Sub, Get,
Set, AddHandler, Operator, RemoveHandler, or RaiseEvent. In this line, we defined
the Main sub-procedure. This marks the entry point in all VB.NET programs. It
defines what the module will do when it is executed.
5. This is where we have specified the behavior of the primary method. The WriteLine
method belongs to the Console class, and it is defined inside the System namespace.
Remember this was imported into the code. This statement makes the program print
the text Hello World on the console when executed.
6. This line will prevent the screen from closing or exiting soon after the program has
been executed. The screen will pause and wait for the user to perform an action to
close it.
7. Closing the main sub-procedure.
8. Ending the module.
8
1.4 Creating a VB.Net project
To write your code, you need to create a new project. The following steps can help you
achieve this:
Step 1) Open Visual Studio, and click the File menu, Choose New then Project from the
toolbar.
Step 2) On the new window, click Visual Basic from the left vertical navigation pane.
Choose Window Forms Application.
Step 3) Give it a name and click the OK button. The project will be created.
You will have created a Windows Form Application project. This type of project will allow
you to create a graphical user interface by dragging and dropping elements.
You may need to create an application that runs on the console. This requires you to create a
Console Application project. The following steps can help you achieve this:
9
Step 1) Open Visual Studio, and click the File menu, Choose New then Project from the
toolbar.
Step 2) On the new window, click Visual Basic from the left vertical navigation pane.
Choose Console Application.
Step 3) Give it a name and click the OK button. The project will be created.
1.4.1 Summary
A VB.NET program is composed of various parts.
After importing a namespace into a program, it becomes possible for us to use all the
methods and functions that have been defined in that module.
Every VB.NET program must have a module.
The VB.NET compiler ignores comments.
We can have more than one procedures in a VB.NET program.
10
1.5 VB.NET OBJECT ORIENTED CONCEPTS
1.5.1 Classes and Objects
A class is like a blank canvas or a template for the object that you will create. An object is an
instance of a class, and so all objects are unique but similar. In VB.NET, we use classes to
define a blueprint for a data type. It does not mean that a class definition is a data definition,
but it describes what an object of that class will be made of and the operations that we can
perform on such an object.
An object is an instance of a class. The class members are the methods and variables defined
within the class.
A class is a pattern that we use to create objects. It defines their properties and abilities.
An object created according to a class is called an instance. Instances have the same interface
as the class according to which they were created, but they mutually differ in their internal data
(fields). For example, let's consider a Human class and creating the carl and jack instances
from it. Both instances will have the same fields as the class (e.g. name and age) and methods
(goToWork() and greet()), but the values in them will be different. For example, the first
instance will have the value "Carl" in the name attribute and 22 in age, the second will have
the values Jack and 45.
11
Public Class person
Public firstname As String
Public lastname As String
Public eyecolour As String
Public haircolour As String
Public Sub setvalues(ByVal first As String, ByVal last As String, ByVal eye As String,
ByVal hair As String)
firstname = first
lastname = last
eyecolour = eye
haircolour = hair
End Sub
End Class
Public Class Form1
bob.setvalues("PAUL ", " NDIP ", " BROWN", " BLACK ")
MessageBox.Show("Bobs hair colour is " & bob.haircolour)
End Sub
End Class
To define a class, we use the Class keyword, which should be followed by the name of the
class, the class body, and the End Class statement. This is described in the following syntax:
From the above code, the class name is Person and the object is bob.
Imports System
Module Module1
Class Figure
Public length As Double
Public width As Double
End Class
Sub Main()
Dim Rectangle As Figure = New Figure()
Dim area As Double = 0.0
Rectangle.length = 8.0
Rectangle.width = 7.0
area = Rectangle.length * Rectangle.width
Console.WriteLine("Area of Rectangle is : {0}", area)
Console.ReadKey()
End Sub
End Module
Example 2:
Explanation of Code:
1. Creating a module named Module1.
2. Creating a class named Figure.
12
3. Creating a class member named length of type Double. Its access level has been set to
public meaning that it will be accessed publicly.
4. Creating a class member named breadth of type Double. Its access level has been set
to public meaning that it will be accessed publicly.
5. Ending the class.
6. Creating the main sub-procedure.
7. Creating an object named Rectangle. This object will be of type figure, meaning that
it will be capable of accessing all the members defined inside the Figure class.
8. Defining a variable named area of type Double and initializing its value to 0.0.
9. Accessing the length property defined in the Figure class and initializing its value to
8.0.
10. Accessing the width property defined in the Figure class and initialize its value to 7.0.
11. Calculating the area of the rectangle by multiplying the values of length and width.
The result of this calculation will be assigned to the area variable.
12. Printing some text and the area of the rectangle on the console.
13. Pausing the console waiting for a user to take action to close it.
14. Ending the sub-procedure.
15. Ending the class.
1.5.2 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
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.
13
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.
13. End of the main sub-procedure.
14. End of the module.
1.5.3 Methods
Methods are functions/procedures defined inside the body of a class. They are used to perform
operations with the attributes of our objects. For example, we might have a Connect method in our
AccessDatabase class. We need not to be informed how exactly Connect connects to the database.
We only know that it is used to connect to a database. This is essential in dividing responsibilities in
programming, especially in large applications.
Module Example
Class Circle
Sub Main()
Dim c As New Circle
c.SetRadius(5)
Console.WriteLine(c.Area())
End Sub
End Module
We have one member field. It is the Radius of the circle. The Public keyword is an access
specifier. It tells that the variable is fully accessible from the outside world.
This is the SetRadius() method. It is a normal Visual Basic procedure. The Me variable is a
special variable, which we use to access the member fields from methods.
The Area() method returns the area of a circle. The Math.PI is a built-in constant.
14
1.5.4 Methods Access Modifiers
Access modifiers set the visibility of methods and member fields. Visual Basic has five access modifiers:
Public, Protected, Private, Friend, and ProtectedFriend. Public members can be
accessed from anywhere. Protected members can be accessed only within the class itself and by
inherited and parent classes. Friend members may be accessed from within the same assembly (exe
or DLL). ProtectedFriend is a union of protected and friend modifiers.
Module Module1
Class Person
End Class
Sub Main()
Dim p As New Person
p.Name = "Hassan"
p.SetAge(17)
Console.WriteLine("{0} is {1} years old", p.Name, p.GetAge)
Console.ReadKey()
End Sub
End Module
The Me keyword provides a way to refer to the specific instance of a class or structure in which the
code is currently executing. Me behaves like either an object variable or a structure variable referring
to the current instance. In PHP, Me is the same as $this->. {x} is used to define the Xth variable in a
string.
In the above program, we have two member fields. One is declared Public, the other
Private.
If a member field is Private, the only way to access it is via methods. If we want to modify
an attribute outside the class, the method must be declared Public. This is an important
aspect of data protection.
The SetAge() method enables us to change the private Age variable from outside of the class
definition.
15
Dim p as New Person
p.Name = "Hassan"
We create a new instance of the Person class. Because the Name attribute is Public, we can
access it directly. However, this is not recommended.
p.setAge(17)
The SetAge() method modifies the Age member field. It cannot be accessed or modified
directly, because it is declared Private.
1.5.5 Inheritance
The inheritance is a way to form new classes using classes that have already been defined. The newly
formed classes are called derived classes, the classes that we derive from are called base classes.
Important benefits of inheritance are code reuse and reduction of complexity of a program. The
derived classes (descendants) override or extend the functionality of base classes (ancestors).
Module Module1
Class Base
Public Name As String = "Hassan"
Protected Age As Integer = 17
Private IsDefined As Boolean = True
End Class
Class Derived
Inherits Base
Sub Main()
Dim drv As Derived = New Derived
drv.Info()
End Sub
End Module
In the preceding program, we have a Derived class, which inherits from the Base class. The
Base class has three member fields. All with different access modifiers. The IsDefined
member is not inherited. The Private modifier prevents this.
Class Derived
Inherits Base
16
The class Derived inherits from the Base class.
Console.WriteLine(Me.Name)
Console.WriteLine(Me.Age)
'Console.WriteLine(Me.IsDefined)
The Public and the Protected members are inherited by the Derived class. They can be
accessed. The Private member is not inherited. The line accessing the member field is
commented. If we uncommented the line, it would not compile.
Module Module1
Class Sum
Public Function GetSum() As Integer
Return 0
End Function
Sub Main()
Console.WriteLine(s.GetSum())
Console.WriteLine(s.GetSum(20))
Console.WriteLine(s.GetSum(20, 30))
End Sub
End Module
Console.WriteLine(s.getSum())
Console.WriteLine(s.getSum(20))
Console.WriteLine(s.getSum(20, 30))
17
1.5.7 Constructor
A constructor is a special kind of a method. It is automatically called, when the object is created. The
purpose of the constructor is to initiate the state of the object. The name of the constructor in Visual
Basic is New. The constructors are methods, so they can be overloaded too (see method overloading
above).
Module Module1
Class Being
Sub New()
Console.WriteLine("Being is being created")
End Sub
End Class
Sub Main()
Dim b As New Being
Dim t As New Being("Hassan")
End Sub
End Module
We have a Being class. This class has two constructors. The first one does not take
parameters, the second one takes one parameter.
An instance of the Being class is created. This time the constructor without a parameter is
called upon object creation.
18
1.5.8 The ToString() Method
Each object has a ToString() method. It returns a human-readable representation of the object.
The default implementation returns the fully qualified name of the type of the Object. Note that when
we call the Console.WriteLine() method with an object as a parameter, the ToString() is being
called.
Module Module1
Class Being
Public Overrides Function ToString() As String
Return "This is Being Class"
End Function
End Class
Sub Main()
Dim b As New Being
Dim o As New Object
Console.WriteLine(o.ToString())
Console.WriteLine(b.ToString())
Console.WriteLine(b)
Console.ReadKey()
End Sub
End Module
We have a Being class in which we override the default implementation of the ToString()
method.
Each class created inherits from the base Object. The ToString() method belongs to this
Object class. We use the Overrides keyword to inform that we are overriding a method.
Console.WriteLine(o.ToString())
Console.WriteLine(b.ToString())
Console.WriteLine(b)
As we have specified earlier, calling the Console.WriteLine() on the object will call its
ToString() method.
Abstract classes cannot be instantiated. If a class contains at least one abstract method, it
must be declared abstract too. Abstract methods cannot be implemented, they merely declare
the methods' signatures. When we inherit from an abstract class, all abstract methods must be
19
implemented by the derived class. Furthermore, these methods must be declared with the
same of less restricted visibility.
Unlike Interfaces, abstract classes may have methods with full implementation and may also
have defined member fields. So abstract classes may provide a partial implementation.
Programmers often put some common functionality into abstract classes. And these abstract
classes are later subclassed to provide more specific implementation. For example, the Qt
graphics library has a QAbstractButton, which is the abstract base class of button widgets,
providing functionality common to buttons. Buttons Q3Button, QCheckBox, QPushButton,
QRadioButton, and QToolButton inherit from this base abstract class.
20
Module Module1
MustInherit Class Drawing
Protected x As Integer = 0
Protected y As Integer = 0
Class Circle
Inherits Drawing
End Class
Sub Main()
We have an abstract base Drawing class. The class defines two member fields, defines one
method and declares one method. One of the methods is abstract, the other one is fully
implemented. The Drawing class is abstract, because we cannot draw it. We can draw a
circle, a dot or a square. The Drawing class has some common functionality to the objects
that we can draw.
21
An abstract method is preceded with a MustOverride keyword.
Class Circle
Inherits Drawing
A Circle is a subclass of the Drawing class. It must implement the abstract Area() method.
1.5.10 Polymorphism
The polymorphism is the process of using an operator or function in different ways for
different data input. In practical terms, polymorphism means that if class B inherits from
class A, it doesn't have to inherit everything about class A; it can do some of the things that
class A does differently.
ReadOn RemoveHa
Error Event Exit False ReDim REM
ly ndler
22
GetXMLName Shadow
Function Get GetType Set Shared Short
space s
Struct Struct
ure ure
Impleme Implements String Sub
If If() Constrain Statemen
nts Statement
t t
Impor
Imports
ts SyncLo
(.NET In (Generic Then Throw To
(XML In ck
Namespace Modifier)
Namesp
and Type)
ace)
Integ Interfa TryCas TypeOf…I
Inherits Is True Try
er ce t s
UInteg
IsNot Let Lib Like ULong UShort Using
er
Varian
Long Loop Me Mod Wend When While
t
Modul
e MustInh MustOverri Wideni WithEv WriteOnl
Module With
Stateme erit de ng ents y
nt
MyCla Xor #Const #Else #ElseIf
MyBase NameOf Namespace
ss
New
New #End #If = &
Narrowing Constrai Next
Operator
nt
Next (in NotInherit &= * *= /
Not Nothing
Resume) able
NotOverri Objec /= \ \= ^
Of On
dable t
Optio Optiona ^= + += -
Operator Or
n l
Out
(Generi >> >>=
Overloa Overridabl -= <<
OrElse c Operator Operator
ds e
Modifie
r)
End Sub
End Module
23
Your code goes between the Sub Main() and End Sub. In VB, lines does not end with a semi-
colon; compared to C# and most other languages, VB is kept simple!
1.7.1 Comments
Single line comments start with an apostrophe (')
There are no block comments in VB
XML comments start with three apostrophes; these are useful for documentation purposes
#End Region
Now it is time to write your first program. Between the Sub Main() and End Sub enter the
following:
24
Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59
PM on December 31, 9999
Decimal 16 bytes 0 through +/-79,228,162,514,264,337,593,543,950,335
(+/-7.9...E+28) with no decimal point; 0 through +/-
7.9228162514264337593543950335 with 28 places to the
right of the decimal
Double 8 bytes -1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values
Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed)
Long 8 bytes -9,223,372,036,854,775,808 through
9,223,372,036,854,775,807(signed)
Object 4 bytes on 32- Any type can be stored in a variable of type Object
bit platform
8 bytes on 64-
bit platform
SByte 1 byte -128 through 127 (signed)
Short 2 bytes -32,768 through 32,767 (signed)
Single 4 bytes -3.4028235E+38 through -1.401298E-45 for negative
values;
25
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.
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
Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"
26
1.9 Accepting Enteries From The User
When creating an application, you may need a way of getting input from the user. This can be done
using the ReadLine function of the Console class in System namespace. Once you have received the
input from the user, you are required to assign it to a variable. For example:
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
In the above example, we have defined a variable named message. The message read from the
console has been assigned to that variable.
Exercise: Write a program to accept 2 numbers from the user and display their sum.
1.10 Constants
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.
Definition: Const constantname [ As datatype ] = initializer
Examples:
Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415
1.11 Operators
An operator refers to a symbol that instructs the compiler to perform a specific logical or
mathematical manipulation. The operator performs the operation on the provided operands.
Microsoft VB.Net comes with various types of operators.
VB.Net is rich in built-in operators and provides following types of commonly used operators
Arithmetic Operators
Comparison Operators
Logical/Bitwise Operators
Bit Shift Operators
Assignment Operators
Miscellaneous Operators
27
Symbol Description
MOD known as the modulus operator. It returns the remainder after division.
Exercise: Take x= 10 and y=6, write a program that will use all the above 6 arithmetic
operators and display the result for every operation.
= for checking whether the two operands have equal values or not. If yes,
the condition will become true.
<> for checking if the value of the left operand is greater than that of the
right operand. then condition will become true.
> for checking whether the value of the left operand is less than that of the
right operand. If yes, the condition will become true.
< for checking whether the value of the left operand is greater than or
equal to that of the right operand. If yes, the condition will become true.
>= for checking whether the two operands have equal values or not. If yes,
the condition will become true.
<= for checking whether the value of the left operand is less than or equal to
that of the right operand. If yes, the condition will become true.
Exercise: Take x= 10 and y=6, write a program that will use all the above 6 arithmetic
operators and display the result for every operation.
Hint: To use the conditional statement… (See Conditional Statements on Section 1.12),
If (condition) Then
Code(s)
Else
Code(s)
End If
28
1.11.3 Logical/Bitwise Operators
These operators help us in making logical decisions.
They include:
And known as the logical/bitwise AND. Only true when both conditions
are true.
AndAlso It is also known as the logical AND operator. Only works with
Boolean data by performing short-circuiting.
OrElse It is also known as the logical OR operator. Only works with Boolean
data by performing short-circuiting.
Step 1) Create a new console application. If you don't know how to do it, visit our previous
tutorial on Data Types and Variables.
Sub Main()
29
If (var_y Or var_z) Then
Console.WriteLine("var_y Or var_z - is true")
End If
'Only logical operators
If (var_w AndAlso var_x) Then
Console.WriteLine("var_w AndAlso var_x - is true")
End If
If (var_w OrElse var_x) Then
Console.WriteLine("var_w OrElse var_x - is true")
End If
var_w = False
var_x = True
If (var_w And var_x) Then
Console.WriteLine("var_w And var_x - is true")
Else
Console.WriteLine("var_w And var_x - is not true")
End If
If (Not (var_w And var_x)) Then
Console.WriteLine("var_w And var_x - is true")
End If
Console.ReadLine()
End Sub
Step 3) Run the code by clicking the Start button from the toolbar. You will get the following
window:
30
Explanation of Code:
31
3. Declaring a Boolean variable var_w with a value of True.
4. Declaring a Boolean variable var_x with a value of True.
5. Declaring an integer variable var_y with a value of 5.
6. Declaring an integer variable var_z with a value of 20.
7. Performing And operation on values of variable var_w and var_x. We have used the If…Then
condition to take action based on the result of the operation.
8. Text to print on the console if the result of the above operation is True.
9. Ending the If statement.
10. Performing Or operation on values of variable var_w and var_x. We have used the If…Then
condition to take action based on the result of the operation.
11. Text to print on the console if the result of the above operation is True.
12. Ending the If statement.
13. Performing Xor operation on values of variable var_w and var_x. We have used the If…Then
condition to take action based on the result of the operation.
14. Text to print on the console if the result of the above operation is True.
15. Ending the If statement.
16. Performing And operation on values of variable var_y and var_z. We have used the If…Then
condition to take action based on the result of the operation.
17. Text to print on the console if the result of the above operation is True.
18. Ending the If statement.
19. Performing Or operation on values of variable var_y and var_z. We have used the If…Then
condition to take action based on the result of the operation.
20. Text to print on the console if the result of the above operation is True.
21. Ending the If statement.
22. A comment. The compiler will skip this.
23. Performing AndAlso operation on values of variable var_w and var_x. We have used the
If…Then condition to take action based on the result of the operation.
24. Text to print on the console if the result of the above operation is True.
25. Ending the If statement.
26. Performing OrElso operation on values of variable var_w and var_x. We have used the
If…Then condition to take action based on the result of the operation.
27. Text to print on the console if the result of the above operation is True.
28. Ending the If statement.
29. Changing the value of variable w from true to False.
30. The value of variable var_x will remain to be True.
31. Performing And operation on values of variables var_w and var_x. We have used the
If…Then condition to take action based on the result of the operation.
32. Text to print on the console if the result of the above operation is True.
33. Else part to be executed if the above If the condition is not True.
34. Text to print on the console if the result of the above If the operation is False. Then it is
under the Else statement.
35. Ending the If statement.
36. Performing And operation on values of variables var_w and var_x then reversing the result
using the Not operator. We have used the If…Then condition to take action based on the
result of the operation.
37. Text to print on the console if the result of the above operation is True.
38. Ending the If statement.
39. Accept input from the user via the keyboard.
These operators are used for performing shift operations on binary values.
32
Bit-shit operatiors Details
And Known as the Bitwise AND Operator. It copies a bit to result if it is found in
both operands.
Xor The Binary XOR Operator. For copying a bit if set in one of the operands
rather than both.
= the simple assignment operator. It will assign values from the left
side operands to the right side operands.
+= known as the Add AND assignment operator. It will add the right
operand to the left operand. Then the result will be assigned to
the left operand.
Module Module1
Sub Main()
Dim x As Integer = 5
Dim y As Integer
y = x
Console.WriteLine(" y = x gives y = {0}", y)
y += x
Console.WriteLine(" y += x gives y = {0}", y)
y -= x
33
Console.WriteLine(" y -= x gives y = {0}", y)
y *= x
Console.WriteLine(" y *= x gives y = {0}", y)
Console.ReadLine()
End Sub
End Module
GetType This operator gives the Type of objects for a specified expression.
For example:
Module Module1
Sub Main()
Dim x As Integer = 5
Console.WriteLine(GetType(Integer).ToString())
Console.WriteLine(GetType(String).ToString())
Console.WriteLine(GetType(Double).ToString())
End Sub
End Module
1.11.8 Summary
VB.NET supports the use of operators to perform arithmetic, logical, and comparison
operations.
Operators are divided into various categories.
Operators operate on operands.
34
False question about a property, a variable, or another piece of data in the program code For example,
the conditional expression Price < 100 evaluates to True if the Price variable contains a value that is
less than 100, and it evaluates to False if Price contains a value that is greater than or equal to 100.
When a conditional expression is used in a special block of statements called a decision structure, it
controls whether other statements in your program are executed and in what order they’re executed
You can use an If ... Then decision structure to evaluate a condition.
1.12.1 If Statement
If condition1 Then
statements executed if condition1 is True
ElseIf condition2 Then
statements executed if condition2 is True
[Additional ElseIf conditions and statements can be placed here]
Else
statements executed if none of the conditions is True
End If
Example 1: the Module below accepts a character from the user and does a select.. case
Module Module1
Sub Main()
Dim grade As Char
grade = Console.ReadLine
35
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module
Example 2: The next example uses an exception (try… catch) to receive input from the keyboard and
processes it.
Module Module1
Sub Main()
Dim age As Byte
Try
age = Console.ReadLine()
Catch
Console.WriteLine("Invalid value")
End
End Try
End Sub
End Module
1.13 Loops
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. In VB, the
following loops exist: Do loop, While loop, For….next loop, For each … next loop, With loop
1.13.1 For Loop
This loop will allow you to execute any code a certain amount of times. When the number of cycles is
known before the loop is initiated, we can use the For Next statements. In this construct we declare
a counter variable, which is automatically increased or decreased in value during each repetition of
the loop.
Syntax:
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
Next
Examples:
Sub Main()
Dim i As Integer = 0
For i = 0 To 9
Console.WriteLine("The value of i is: {0}", i)
Next
36
Console.ReadLine()
End Sub
Sub Main()
For i As Integer = 0 To 9
Console.WriteLine("The value of i is: {0}", i)
Next
Console.ReadLine()
End Sub
For i As Integer = 0 To 9
Console.WriteLine(i)
Next
We initiate the counter i to zero. The Next statement increases the counter by one until the
counter equals to 9.
Visual Basic has an optional Step keyword. It controls how the counter variable is going to
be increased or decreased.
Sub Main()
For i As Integer = 9 To 0 Step -1
Console.WriteLine(i)
Next
End Sub
The step may be a negative number too. We initiate the counter to 9. Each iteration the
counter is decreased by the step value.
1.13.2 Do…While Loop
This loop will allow you to execute any code a certain amount of times. When the number of cycles is
known before the loop is initiated, we can use the For Next statements. In this construct we declare
a counter variable, which is automatically increased or decreased in value during each repetition of
the loop.
Syntax:
Do
[ statements ]
Loop { While or Until } condition
Sub Main()
Dim a As Integer = 0
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 9)
Console.ReadLine()
End Sub
The program would behave in same way, if you use an Until statement, instead of While
37
Sub Main()
Dim a As Integer = 0
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop Until (a = 9)
Console.ReadLine()
End Sub
Example 2:
Sub Main()
Dim numbers() As Integer = {1, 3, 5, 7, 9}
38
Dim a As Integer
With object
[ statements ]
End With
Module Module1
Public Class Book
Public Property Name As String
Public Property Lecturer As String
Public Property Speciality As String
End Class
Sub Main()
Dim aBook As New Book
With aBook
.Name = "VB.Net Programming"
.Lecturer = "Paul Peter"
.Speciality = "Software Engineering"
End With
With aBook
Console.WriteLine(.Name)
Console.WriteLine(.Lecturer)
Console.WriteLine(.Speciality)
End With
Console.ReadLine()
End Sub
End Module
1.14 Strings
In VB.Net, you can use strings as array of characters, however, more common practice is to
use the String keyword to declare a string variable. The string keyword is an alias for the
System.String class.
Example 1:
39
Sub Main()
Dim str1 As String = "Cameroon is in "
Dim str2 As String = " Africa"
Console.WriteLine(str1 + str2)
Sub Main()
Dim str As String = "Visual Basic"
Dim n As Integer = Len(str)
Dim l As String = Left(str, 6)
Dim r As String = Right(str, 5)
Dim repl As String = Replace(str, "Basic", "form")
This call of the Left() function returns 6 characters from the left of the string. In our case,
"Visual".
40
Dim r As String = Right(str, 5)
Strings are immutable in Visual Basic. When we use the Replace() function, we return a
new modified string, in which the first string is replaced with the second one.
In our program, we will join and split strings with these two functions.
Dim langs As String = Join(items, ",")
All words from the array are joined. We build one string from them. There will be a comma
character between each two words.
Dim ls() As String = Split(langs, ",")
As a reverse operation, we split the langs string. The Split() function returns an array of
words, delimited by a character. In our case it is a comma character.
41
Console.WriteLine(str.ToUpper)
Console.WriteLine(str.ToLower)
Console.ReadLine()
End Sub
End Module
The Contains() method returns True if the string contains a specific character.
Console.WriteLine(str.IndexOf("e"))
Console.WriteLine(str.ToUpper)
Console.WriteLine(str.ToLower)
Letters of the string are converted to uppercase with the ToUpper method and to lowercase
with the ToLower method.
Module Module1
Sub Main()
42
Console.WriteLine(str Is copied) ' Prints False
The Is operator compares the two reference objects. Therefore comparing a copied string to
the original string returns False. Because they are two distinct objects.
1.15 Arrays
Arrays are collections of data. A variable can hold only one item at a time. Arrays can hold
multiple items. These items are called elements of the array. Arrays store data of the same data type.
Each element can be referred to by an index. Arrays are zero based. The index of the first element is
zero.
Arrays are used to store data of our applications. We declare arrays to be of a certain data
type. We specify their length. And we initialize arrays with data. We have several methods for working
with array. We can modify the elements, sort them, copy them or search them.
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}
Example 1:
Dim numbers(5), i As Integer
numbers(0) = 3
numbers(1) = 2
numbers(2) = 1
numbers(3) = 5
numbers(4) = 6
For i = 0 To numbers.Length - 1
Console.WriteLine(numbers(i))
Next
Console.ReadLine()
Example 2:
Sub Main()
Dim names() As String = {"Hassan", "Peter", _
"Ulrich", "Graig", "Carlson", "Smith", _
"Ingrid", "Audrey"}
43
Dim numbers() As Integer = {1, 3, 5, 7, 9}
Dim a As Integer
Sub Main()
Dim names() As String = {"Hassan", "Ulrich", "Roy", "Smith"}
Array.Sort(names)
Console.Write(vbNewLine)
Array.Reverse(names)
Array.Reverse(names)
The Reverse() method reverses the sequence of the elements in the entire one-dimensional
array.
We have ordered the names in ascending and descending order.
The following example uses SeValue(), GetValue(), IndexOf(), Copy() and Clear()
methods.
Sub Main()
names.SetValue("Audrey", 1)
names.SetValue("Ingrid", 3)
Console.WriteLine(names.GetValue(1))
Console.WriteLine(names.GetValue(3))
44
Console.WriteLine(Array.IndexOf(names, "Ingrid"))
Console.Write(vbNewLine)
Array.Clear(names, 0, 2)
Console.WriteLine(names.GetValue(1))
Console.WriteLine(names.GetValue(3))
We retrieve the values from the array with the GetValue() method.
Console.WriteLine(Array.IndexOf(names, "Ingrid"))
The IndexOf() method returns an index for the first occurrence of a specific value.
Array.Clear(names, 0, 2)
The Clear() method clears elements from the array. It takes three parameters, the array, the
start index and the number of elements from the index to clear.
In this part of the Visual Basic tutorial, we worked with arrays. We described various types of
arrays and methods to work with them.
A procedure and function is a piece of code in a larger program. They perform a specific task.
The advantages of using procedures and functions are:
Reducing duplication of code
45
Decomposing complex problems into simpler pieces
Improving clarity of the code
Reuse of code
Information hiding
Sub SimpleProcedure()
Console.WriteLine("Simple Sub procedure")
End Sub
End Module
This example shows basic usage of procedures. In our program, we have two procedures. The Main()
procedure and the user defined SimpleProcedure(). As we already know, the Main() procedure
is the entry point of a Visual Basic program.
Each procedure has a name. Inside the Main() procedure, we call our user defined
SimpleProcedure() procedure.
Procedures are defined outside the Main() procedure. Procedure name follows the Sub
statement. When we call a procedure inside the Visual Basic program, the control is given to
that procedure. Statements inside the block of the procedure are executed.
Procedures can take optional parameters.
Sub Main()
Dim x As Integer = 55
Dim y As Integer = 32
Addition(x, y)
End Sub
Here we call the Addition() procedure and pass two parameters to it. These parameters are
two Integer values.
Sub Addition(ByVal k As Integer, ByVal l As Integer)
Console.WriteLine(k+l)
End Sub
We define a procedure signature. A procedure signature is a way of describing the
parameters and parameter types with which a legal call to the function can be made. It
contains the name of the procedure, its parameters and their type, and in case of functions
46
also the return value. The ByVal keyword specifies how we pass the values to the procedure.
In our case, the procedure obtains two numerical values, 55 and 32. These numbers are added
and the result is printed to the console.
1.16.2 Functions
A function is a block of Visual Basic statements inside Function, End Function
statements. Functions return values.
There are two basic types of functions. Built-in functions and user defined ones. The built-in
functions are part of the Visual Basic language. There are various mathematical, string or
conversion functions.
Module Module1
Dim result As Integer
Sub Main()
Dim x As Integer = 55
Dim y As Integer = 32
result = Addition(x, y)
Console.WriteLine(result)
End Sub
Addition function is called. The function returns a result and this result is assigned to the result
variable.
Function Addition(ByVal k As Integer, ByVal l As Integer) As Integer
Return k+l
End Function
This is the Addition function signature and its body. It also includes a return data type, for the returned
value. In our case is an Integer. Values are returned to the caller with the Return keyword.
Example:
Following code snippet shows a function FindMax that takes two integer values and returns
the larger of the two.
Module Module1
Dim result As Integer
Sub Main()
Dim x As Integer = 55
Dim y As Integer = 32
result = FindMax(x, y)
Console.WriteLine(result)
Console.ReadKey()
47
End Sub
Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords - Try, Catch, Finally and Throw.
Try − A Try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more Catch blocks.
Catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The Catch keyword indicates the
catching of an exception.
Finally − The Finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
Throw − A program throws an exception when a problem shows up. This is done
using a Throw keyword.
Syntax:
Assuming a block will raise an exception, a method catches an exception using a combination
of the Try and Catch keywords. A Try/Catch block is placed around the code that might
generate an exception. Code within a Try/Catch block is referred to as protected code, and the
syntax for using Try/Catch looks like the following −
Try
[ tryStatements ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Finally
[ finallyStatements ] ]
End Try
Example:
Module Module1
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
48
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
49
PART 2 – FORMS AND CONTROL ELEMENTS
50