0% found this document useful (0 votes)
3 views

Chapter One

This document is a comprehensive handout on VB.NET programming, covering its history, features, advantages, and disadvantages, as well as practical exercises and applications. It introduces the Integrated Development Environment (IDE) for VB.NET, explains console programming, and guides users on creating projects. The content is structured into sections that detail various programming concepts, syntax, data types, and control elements within VB.NET.

Uploaded by

Ngu Tah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Chapter One

This document is a comprehensive handout on VB.NET programming, covering its history, features, advantages, and disadvantages, as well as practical exercises and applications. It introduces the Integrated Development Environment (IDE) for VB.NET, explains console programming, and guides users on creating projects. The content is structured into sections that detail various programming concepts, syntax, data types, and control elements within VB.NET.

Uploaded by

Ngu Tah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

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.1 History of VB.NET .................................................................................................................... 5

1.1.2 VB.NET Features ....................................................................................................................... 6

1.1.3 Advantages of VB.NET ............................................................................................................. 6

1.1.4 Disadvantages of VB.NET ......................................................................................................... 6

1.1.5 Summary: ................................................................................................................................... 7

1.2 Integrated Development Environment (IDE) for VB.NET ......................................................... 7


1.3 VB.NET PROGRAMMING WITH THE CONSOLE ................................................................ 8
1.4 Creating a VB.Net project .............................................................................................................. 9
1.4.1 Summary .................................................................................................................................. 10

1.5 VB.NET OBJECT ORIENTED CONCEPTS ............................................................................ 11


1.5.1 Classes and Objects.................................................................................................................. 11

1.5.2 Structures ................................................................................................................................. 13

1.5.3 Methods ................................................................................................................................... 14

1.5.4 Methods Access Modifiers ....................................................................................................... 15

1.5.5 Inheritance ............................................................................................................................... 16

1.5.6 Method Overloading ................................................................................................................ 17

1.5.7 Constructor .............................................................................................................................. 18

1.5.8 The ToString() Method ............................................................................................................. 19

1.5.9 Abstract Classes and Methods ................................................................................................. 19

1.5.10 Polymorphism ........................................................................................................................ 22

1.5.11 Advantages of Object-Oriented Programming....................................................................... 22

1.6 VB.Net Reserved Keywords ......................................................................................................... 22


1.7 Visual Basic Syntax ....................................................................................................................... 23
1.7.1 Comments ................................................................................................................................ 24

1.7.2 Organizing Code ....................................................................................................................... 24

1.7.3 Write Your First Program ......................................................................................................... 24

1
1.8 Visual Basic Data Types ............................................................................................................... 24
1.8.1 Type Conversion Functions ...................................................................................................... 25

1.9 Visual Basic Variables .................................................................................................................. 26


1.9.1 Variable Initialization ............................................................................................................... 26

1.9 Accepting Enteries From The User ............................................................................................. 27


1.10 Constants ..................................................................................................................................... 27
1.11 Operators ..................................................................................................................................... 27
1.11.1 Arithmetic Operators ............................................................................................................. 27

1.11.2 Comparison Operators........................................................................................................... 28

1.11.3 Logical/Bitwise Operators ...................................................................................................... 29

1.11.4 Bit Shift Operators ................................................................................................................. 32

1.11.5 Assignment Operators ........................................................................................................... 33

1.11.7 Miscellaneous Operators ....................................................................................................... 34

1.11.8 Summary ................................................................................................................................ 34

1.12 Conditional Statements............................................................................................................... 34


1.12.1 If Statement ........................................................................................................................... 35

1.12.2 Select Statement .................................................................................................................... 35

1.13 Loops ............................................................................................................................................ 36


1.13.1 For Loop................................................................................................................................. 36

1.13.2 Do…While Loop ................................................................................................................... 37

1.13.3 While Loop ............................................................................................................................ 38

1.13.4 For…Each Loop..................................................................................................................... 38

1.13.5 With…End Loop .................................................................................................................... 39

1.14 Strings .......................................................................................................................................... 39


1.14.1 Creating a String Object ......................................................................................................... 39

1.14.2 String Functions ..................................................................................................................... 40

1.14.3 Join and Split Functions ......................................................................................................... 41

1.14.4 String Methods....................................................................................................................... 41

1.14.5 Copy vs Clone ......................................................................................................................... 42

1.15 Arrays........................................................................................................................................... 43
1.15.1 Creating Arrays in VB.Net ...................................................................................................... 43

1.15.2 Array Methods ....................................................................................................................... 44

2
1.16 Functions and Subs Procedures ................................................................................................. 45
1.16.1 Sub Procedures....................................................................................................................... 46

1.16.2 Functions ................................................................................................................................ 47

1.16.3 Exception Handling ................................................................................................................. 48


PART 2 – FORMS AND CONTROL ELEMENTS............................................................................. 50

3
PREREQUISITES
- Be able to write an Algorithm
- Understand basic programming syntaxes

OBJECTIVES
At the end of this lesson, you should be able to:

- To give an overview of the Visual Basic IDE features:


Projects, Forms, and Properties; Toolbox and
Controls; Form Layout Window and Properties
Window.
- Write simple programs using the console
- Create forms and control elements
- Develop and compile a software
- Create setup for a computer program

PART 1 – GENERAL INTRODUCTION AND CONSOLE PROGRAMMING

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.

 In 2003, the second version of VB.NET, VB.NET


7.1, was released. This one relied on .NET version 1.1. This version came with a
number of improvements including support for .NET Compact Framework and an
improved reliability and performance of the .NET IDE. VB.NET 2003 was also made
available in the academic edition of Visual Studio.NET and distributed to various
scholars from different countries for free.
 In 2005, VB.NET 8.0 was released. The .NET core portion was dropped from its name
so as to distinguish it from the classical Visual Basic language. This version was named
Visual Basic 2005. This version came with many features since Microsoft wanted this
language to be used for rapid application developers. They also wanted to make it
different from C# language. Some of the features introduced by this version of VB.NET
included partial classes, generics, nullable types, operator overloading, and unsigned
integer support. This version also saw the introduction of the IsNot operator.
 In 2008, VB 9.0 was introduced. This was released together with .NET 3.5. Some of
the features added to this release of VB.NET included anonymous types, true
conditional operator, LINQ support, XML literals, Lambda expressions, extension
methods, and type inference.
 In 2010, Microsoft released VB 2010 (code 10.0). They wanted to use a Dynamic
Language Runtime for this release, but they opted for co-evolution strategy shared
between VB.NET and C# to bring these languages closer to each other.
 In 2012, VB 2012 (code 11.0) was release together with .NET 4.5. Its features included
call hierarchy, iterators, caller data, asynchronous programming with "await" and
"async" statements and the "Global" keyword in the "namespace" statements.
 In 2015, VB 2015 (code 14.0) was released alongside Visual Studio 2015. The "?."
operator was introduced to do inline null checks. A string interpolation feature was also
introduced to help in formatting strings inline.
 In 2017, VB 2017 (code 15.0) was introduced alongside Visual Studio 2017. A better
way of organizing source code in just a single action was introduced.

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.

1.1.3 Advantages of VB.NET


The following are the pros/benefits you will enjoy for coding in VB.NET:
 Your code will be formatted automatically.
 You will use object-oriented constructs to create an enterprise-class code.
 You can create web applications with modern features like performance counters, event
logs, and file system.
 You can create your web forms with much ease through the visual forms designer. You
will also enjoy drag and drop capability to replace any elements that you may need.
 You can connect your applications to other applications created in languages that run
on the .NET framework.
 You will enjoy features like docking, automatic control anchoring, and in-place menu
editor all good for developing web applications.

1.1.4 Disadvantages of VB.NET


Below are some of the drawbacks/cons associated with VB.NET:

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.

1.2 Integrated Development Environment (IDE) for VB.NET


 .NET Framework is a software framework developed by Microsoft that runs primarily
on Microsoft Windows. It includes a large class library called Framework Class
Library and provides language interoperability across several programming
languages. The IDE we shall be using for VB.NET is the Microsoft Visual Studio.
There are also other IDEs for programming VB.NET such as Visual Studio 2010
(VS), Visual Basic 2010 Express (VBE),Visual Web Developer.

Microsoft Visual Studio is an integrated development environment from Microsoft. It is used to


develop computer programs, as well as websites, web apps, web services and mobile apps. The
following programming languages can be used in VS: C#, C++, Visual Basic .NET, J#.

Figure 1 Microsoft Visual Studio Program Process

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.

1.3 VB.NET PROGRAMMING WITH THE CONSOLE


The code below will display Hello World in the console.
Imports System……..1
'prints a statement on the console…….2
Module Module1…………3
Sub Main()……………4
Console.WriteLine("Hello World")……….5
Console.ReadKey()……………..6
End Sub…………..7
End Module…………..8

Figure 2 VB.Net Program Structure

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

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles Button1.Click

Dim bob As New person


bob.firstname = "PAUL"
bob.lastname = "NDIP"
bob.eyecolour = "BROWN"
bob.haircolour = "BLACK"

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

Public Radius As Integer


Public Sub SetRadius(ByVal Radius As Integer)
Me.Radius = Radius
End Sub

Public Function Area() As Double


Return Me.Radius * Me.Radius * Math.PI
End Function
End Class

Sub Main()
Dim c As New Circle
c.SetRadius(5)
Console.WriteLine(c.Area())
End Sub
End Module

In the code example, we have a Circle class. We define two methods.


Public Radius As Integer

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.

Public Sub SetRadius(ByVal Radius As Integer)


Me.Radius = Radius
End Sub

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.

Public Function Area() As Double


Return Me.Radius * Me.Radius * Math.PI
End Function

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

Public Name As String


Private Age As Byte

Public Function GetAge() As Byte


Return Me.Age
End Function

Public Sub SetAge(ByVal Age As Byte)


Me.Age = Age
End Sub

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.

Public Function GetAge() As Byte


Return Me.Age
End Function

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.

Public Sub SetAge(ByVal Age As Byte)


Me.Age = Age
End Sub

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.

Console.WriteLine("{0} is {1} years old", _


p.Name, p.GetAge)

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

Public Sub Info()


Console.WriteLine("This is Derived Class")
Console.WriteLine("Members inherited:")
Console.WriteLine(Me.Name)
Console.WriteLine(Me.Age)
'Console.WriteLine(Me.IsDefined)
Console.ReadKey()
End Sub
End Class

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.

1.5.6 Method Overloading


Method overloading allows the creation of several methods with the same name which differ from
each other in the type of the input. In method overloading, the input parameters of each method
differ from each other.

Module Module1

Class Sum
Public Function GetSum() As Integer
Return 0
End Function

Public Function GetSum(ByVal x As Integer) As Integer


Return x
End Function

Public Function GetSum(ByVal x As Integer, ByVal y As Integer) As Integer


Return x + y
End Function
End Class

Sub Main()

Dim s As Sum = New Sum

Console.WriteLine(s.GetSum())
Console.WriteLine(s.GetSum(20))
Console.WriteLine(s.GetSum(20, 30))

End Sub
End Module

We have three methods called GetSum(). They differ in input parameters.

Public Function GetSum(ByVal x As Integer) As Integer


Return x
End Function
This one above takes one parameter.

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

Sub New(ByVal name As String)


Console.WriteLine("Being {0} is created", name)
Console.ReadKey()
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.

Sub New(ByVal name As String)


Console.WriteLine("Being {0} is created", name)
End Sub

This constructor takes one String parameter.

Dim b As New Being

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.

Public Overrides Function ToString As String


Return "This is Being Class"
End Function

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.

Dim b as New Being


Dim o As New Object

We create two objects. One custom defined and one built-in.

Console.WriteLine(o.ToString())
Console.WriteLine(b.ToString())

We call the ToString() method on these two objects.

Console.WriteLine(b)

As we have specified earlier, calling the Console.WriteLine() on the object will call its
ToString() method.

1.5.9 Abstract Classes and Methods

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

Public MustOverride Function Area() As Double

Public Function GetCoordinates() As String


Return String.Format("x: {0}, y: {1}", _
Me.x, Me.y)
End Function
End Class

Class Circle
Inherits Drawing

Private Radius As Integer

Sub New(ByVal x As Integer, ByVal y As Integer, _


ByVal r As Integer)
Me.x = x
Me.y = y
Me.Radius = r
End Sub

Public Overrides Function Area() As Double


Return Me.Radius * Me.Radius * Math.PI
End Function

Public Overrides Function ToString() As String


Return String.Format("Circle, at x: {0}, y: {1}, radius: {2}", _
Me.x, Me.y, Me.Radius)
End Function

End Class

Sub Main()

Dim c As New Circle(12, 45, 22)


Console.WriteLine(c)
Console.WriteLine("Area of circle: {0}", c.Area())
Console.WriteLine(c.GetCoordinates())
Console.ReadKey()
End Sub
End Module

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.

MustInherit Class Drawing

In Visual Basic, we use the MustInherit keyword to define an abstract class.

Public MustOverride Function Area() As Double

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.

In general, polymorphism is the ability to appear in different forms. Technically, it is the


ability to redefine methods for derived classes. Polymorphism is concerned with the
application of specific implementations to an interface or a more generic base class.

Polymorphism is the ability to redefine methods for derived classes.

1.5.11 Advantages of Object-Oriented Programming


 Object-Oriented Programming provides a clear modular structure for programs which makes it good
for defining abstract data types where implementation details are hidden and the unit has a clearly
defined interface.
 Object-Oriented Programming makes it easy to maintain and modify existing code as new objects can
be created with small differences to existing ones.
 Object-Oriented Programming provides a good framework for code libraries where supplied software
components can be easily adapted and modified by the programmer. This is particularly useful for
developing graphical user interfaces.

1.6 VB.Net Reserved Keywords


Like every programming language, VB.Net has its own reserved keywords which you cannot use them
as variable names or procedures.

End Overri ParamA Partia


Each Else ElseIf Private
Statement des rray l

End Proper Protec RaiseEve


EndIf Enum Erase Public
<keyword> ty ted nt

ReadOn RemoveHa
Error Event Exit False ReDim REM
ly ndler

For (in For


Finally For…N Each…Ne Friend Resume Return SByte Select
ext) xt

22
GetXMLName Shadow
Function Get GetType Set Shared Short
space s

Global GoSub GoTo Handles Single Static Step Stop

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)

1.7 Visual Basic Syntax


Visual Basic has a very simple programming syntax. The language is not case-sensitive and
it is designed for people new to the programming world, making it a good place to start.
Go ahead and start a new VB Console Application and give it the name Syntax. You should
see the following code:
Module Module1
Sub Main()

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

1.7.2 Organizing Code


Organizing code is very important, and comments and regions are very useful. It is considered
good practice to group and comment your code so it is easy for other developers to work on it.
Comments should provide a small description of that piece of code, and regions are useful use
to group code together. To create a region you use the following syntax:
#region "region name"

Other code here..

#End Region

This will be demonstrated further in later tutorials.

1.7.3 Write Your First Program

Now it is time to write your first program. Between the Sub Main() and End Sub enter the
following:

Console.WriteLine("My First Visual Basic Program!")


Console.ReadLine()

Hit F5 to execute of click on the green play button

Console.WriteLine is a system method.

the period (or dot) is called Member Accessor. Example: Me.Age

1.8 Visual Basic 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:
Table 1 VB Data Types (Source: https://www.tutorialspoint.com/vb.net/vb.net_data_types.htm)

Data Type Storage Value Range


Allocation
Boolean Depends on True or False
implementing
platform
Byte 1 byte 0 through 255 (unsigned)
Char 2 bytes 0 through 65535 (unsigned)

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;

1.401298E-45 through 3.4028235E+38 for positive values


String Depends on 0 to approximately 2 billion Unicode characters
implementing
platform
UInteger 4 bytes 0 through 4,294,967,295 (unsigned)
ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned)
User- Depends on Each member of the structure has a range determined by
Defined implementing its data type and independent of the ranges of the other
platform members
UShort 2 bytes 0 through 65,535 (unsigned)

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

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.

1.9 Visual Basic 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.
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
Examples:
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
Dim b As Byte
Dim si As Single
Dim c As Char

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

1.11.1 Arithmetic Operators


You can use arithmetic operators to perform various mathematical operations in VB.NET.
They include:

27
Symbol Description

^ for raising an operand to the power of another operand

+ for adding two operands.

- for subtracting the second operand from the first operand.

* for multiplying both operands.

/ for dividing an operand against another. It returns a floating point result.

\ for dividing an operand against another. It returns an integer result.

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.

1.11.2 Comparison Operators


These operators are used for making comparisons between variables. They include the
following:
Comparison Details
Operators

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

Let us demonstrate how to use these using an example:

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:

Logical/ Bite wise Operator Descriptions

And known as the logical/bitwise AND. Only true when both conditions
are true.

Or known as the logical/bitwise OR. True when any of the conditions is


true.

Not The logical/bitwise NOT. To reverse operand's logical state. If true,


the condition becomes False and vice versa.

Xor bitwise Logical Exclusive OR operator. Returns False if expressions


are all True or False. Otherwise, it returns 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.

IsFalse Determines whether expression evaluates to False.

IsTrue Determines whether expression evaluates to True.

Let us demonstrate how to use these operators using an example:

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.

Step 2) Add the following code:

Sub Main()

Dim var_w As Boolean = True


Dim var_x As Boolean = True
Dim var_y As Integer = 5
Dim var_z As Integer = 20

If (var_w And var_x) Then


Console.WriteLine("var_w And var_x - is true")
End If
If (var_w Or var_x) Then
Console.WriteLine("var_w Or var_x - is true")
End If
If (var_w Xor var_x) Then
Console.WriteLine("var_w Xor var_x - is true")
End If
If (var_y And var_z) Then
Console.WriteLine("var_y And var_z - is true")
End If

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:

Here are screenshots of the above code:

30
Explanation of Code:

1. Creating a module named Module1.


2. Creating the main sub-procedure.

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.

1.11.4 Bit Shift Operators

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.

Or Known as the Binary OR Operator. It copies a bit if found in either operand.

Xor The Binary XOR Operator. For copying a bit if set in one of the operands
rather than both.

Not It is known as the Binary Ones Complement Operator. It is a unary operator


that 'flips' the bits.

1.11.5 Assignment Operators


Assignment Details
Operator

=  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.

=  known as the Subtract AND operator. It will subtract the right


operand from left operand and assign the result to the left
operand.

*=  : known as the Multiply AND operator. It will subtract the right


operand from left operand and assign the result to the left
operand.

Let us demonstrate how to use these operators using an example:

Step 1) Create a new console application.

Step 2) Add the following code:

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

1.11.7 Miscellaneous Operators

There are other operators supported by VB.NET. Let us discuss them:

Miscellaneous Operators Details

GetType This operator gives the Type of objects for a specified expression.

Function Expression  for declaring the code and parameters of a lambda


 expression function.

For example:

Step 1) Create a new console application.

Step 2) Add the following code:

Module Module1

Sub Main()

Dim x As Integer = 5
Console.WriteLine(GetType(Integer).ToString())
Console.WriteLine(GetType(String).ToString())
Console.WriteLine(GetType(Double).ToString())

Dim trippleValue = Function(val As Integer) val * 3


Console.WriteLine(trippleValue(2))
Console.WriteLine(If(x >= 0, "Positive", "Negative"))
Console.ReadLine()

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.

1.12 Conditional Statements


One of the most useful tools for processing information in an event procedure is a conditional
expression A conditional expression is a part of a complete program statement that asks a True-or-

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

1.12.2 Select Statement


The Select statement is a selection control flow statement. It allows the value of a variable or
expression to control the flow of program execution via a multi way branch. It creates multiple
branches in a simpler way than using the combination of If, Else If statements. In C, C++ and
PHP,Java Select Statement is equivalent to Switch….Case. Syntax is given below.
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select

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

Select Case grade


Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else

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

Select Case age


Case 0 To 21
Console.WriteLine("Junior")
Case 22 To 60
Console.WriteLine("Adult")
Case Else
Console.WriteLine("Senior")
End Select

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

In this example, we print numbers 0..9 to the console.

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

In the above example, we print numbers 0..9 in the reverse order.


For i As Integer = 9 To 0 Step -1
Console.WriteLine(i)
Next

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

1.13.3 While Loop


It executes a series of statements as long as a given condition is True.
The syntax for this loop construct is −
While condition
[ statements ]
End While
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is logical true. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following
the loop.
Sub Main()
Dim a As Integer = 0
While a < 9
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
Console.ReadLine()
End Sub

1.13.4 For…Each Loop


It repeats a group of statements for each element in a collection. This loop is used for
accessing and manipulating all elements in an array or a VB.Net collection.
The syntax for this loop construct is −
For Each element [ As datatype ] In group
[ statements ]
Next [ element ]
In the example below, we have created an array called names() of type string and set some
names and loop through every element of the array and display it.
Sub Main()
Dim names() As String = {"Hassan", "Peter", _
"Ulrich", "Graig", "Carlson", "Smith", _
"Ingrid", "Audrey"}

For Each newName As String In names


Console.WriteLine(newName)
Next
Console.ReadLine()
End Sub

Example 2:
Sub Main()
Dim numbers() As Integer = {1, 3, 5, 7, 9}

38
Dim a As Integer

For Each a In numbers


Console.WriteLine(a)
Next
Console.ReadLine()
End Sub

1.13.5 With…End Loop


It is not exactly a looping construct. It executes a series of statements that repeatedly refers to
a single object or structure.
The syntax for this loop construct is −

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.

1.14.1 Creating a String Object


You can create string object using one of the following methods −
 By assigning a string literal to a String variable
 By using a String class constructor
 By using the string concatenation operator (+)
 By retrieving a property or calling a method that returns a string
 By calling a formatting method to convert a value or object to its string representation

Example 1:

39
Sub Main()
Dim str1 As String = "Cameroon is in "
Dim str2 As String = " Africa"

Console.WriteLine(str1 + str2)

Console.WriteLine("The length of the first string is " _


+ str1.Length.ToString() + " characters")
Console.ReadLine()
End Sub
In the above example, the (+) is used for concatenation. Two strings are concatenated. We use the +
operator to add two strings. The (.Length) and Len() functions are used to get the number of characters
in a string. To view all the string functions, simply, type a string variable and enter a dot(.) after the
variable, the IDE with automatically show you all the string functions which can be used in the current
context.
Example 2:
Sub Main()
Dim str1 As String = "Visual Basic"
Dim str2 As String = "visual basic"

Console.WriteLine(String.Compare(str1, str2, True))


Console.WriteLine(String.Compare(str1, str2, False))
Console.ReadLine()
End Sub

1.14.2 String Functions


Visual Basic has useful built-in functions that can be used for working with strings.
Option Strict On

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

Console.WriteLine("The string has {0} characters", n)


Console.WriteLine("The Left function returns {0}", l)
Console.WriteLine("The Right function returs {0}", r)
Console.WriteLine("The Replace function returns {0}", repl)
Console.ReadLine()
End Sub

We introduce four string functions in Visual Basic.


Dim n As Integer = Len(str)

The Len() function returns the number of characters in a string.

Dim l As String = Left(str, 6)

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)

Here we get 5 characters from the right.

Dim repl As String = Replace(str, "Basic", "form")

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.

1.14.3 Join and Split Functions


The Join() and Split() functions are very handy functions.
Imports System
Module Module1
Sub Main()

Dim items() As String = {"C#", "Visual Basic", "Java", "Perl"}

Dim langs As String = Join(items, ",")


Console.WriteLine(langs)

Dim ls() As String = Split(langs, ",")


For Each lang As String In ls
Console.WriteLine(lang)
Next
Console.ReadLine()
End Sub
End Module

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.

For Each lang As String In ls


Console.WriteLine(lang)
Next

1.14.4 String Methods


Apart from string functions, there are several string methods. Some of them provide the same
functionality. As we have already mentioned, strings are not primitive data types. They are
reference types. They are objects and these objects have methods, which can do some work.
Imports System
Module Module1
Sub Main()

Dim str As String = "Determination"


Console.WriteLine(str.Contains("e"))
Console.WriteLine(str.IndexOf("e"))
Console.WriteLine(str.LastIndexOf("i"))

41
Console.WriteLine(str.ToUpper)
Console.WriteLine(str.ToLower)
Console.ReadLine()
End Sub
End Module

We introduce five string methods in the above example.


Console.WriteLine(str.Contains("e"))

The Contains() method returns True if the string contains a specific character.
Console.WriteLine(str.IndexOf("e"))

The IndexOf returns the first index of a letter in the string.


Console.WriteLine(str.LastIndexOf("i"))

The LastIndexOf() methods returns the last index of a letter in a string.

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.

1.14.5 Copy vs Clone


We will describe a difference between two methods. Copy and Clone. The Copy() method
creates a new instance of String with the same value as a specified String. The Clone()
method returns a reference to the string, which is being cloned. It is not an independent copy
of the string on the Heap. It is another reference on the same string.

Module Module1
Sub Main()

Dim str As String = "Visual Basic"

Dim cloned As String = CType(str.Clone(), String)


Dim copied As String = String.Copy(str)

Console.WriteLine(str = cloned) ' Prints True


Console.WriteLine(str = copied) ' Prints True

Console.WriteLine(str Is cloned) ' Prints True


Console.WriteLine(str Is copied) ' Prints False
Console.ReadLine()
End Sub
End Module

Our example demonstrates the difference between the two methods.


Dim cloned As String = CType(str.Clone(), String)
Dim copied As String = String.Copy(str)

The string value is cloned and copied.


Console.WriteLine(str = cloned) ' Prints True
Console.WriteLine(str = copied) ' Prints True

The contents of all three strings are the same.


Console.WriteLine(str Is cloned) ' Prints True

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.

1.15.1 Creating Arrays in VB.Net


To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array

You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya","Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12D, 16UI, "A"c}

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

For Each newName As String In names


Console.WriteLine(newName)
Next
Console.ReadLine()
End Sub
Example 3:
Sub Main()

43
Dim numbers() As Integer = {1, 3, 5, 7, 9}
Dim a As Integer

For Each a In numbers


Console.WriteLine(a)
Next
Console.ReadLine()
End Sub

1.15.2 Array Methods


There are various methods for working with arrays. These methods can be used for retrieving,
modifying data, sorting, copying, searching data. These methods that we use are static
methods of the Array class or member methods of the array objects.

Sub Main()
Dim names() As String = {"Hassan", "Ulrich", "Roy", "Smith"}
Array.Sort(names)

For Each el As String In names


Console.Write(el + " ")
Next

Console.Write(vbNewLine)
Array.Reverse(names)

For Each el As String In names


Console.Write(el + " ")
Next
Console.ReadKey()
End Sub

We have an array of strings.


Array.Sort(names)

The Sort() method sorts the data alphabetically.

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.

Dim names() As String = {"Hassan", "Ulrich", "Roy", "Smith"}


Dim girls(0 To 3) As String

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

Array.Copy(names, girls, names.Length)

For Each el As String In girls


Console.Write(el + " ")
Next

Console.Write(vbNewLine)
Array.Clear(names, 0, 2)

For Each el As String In names


Console.Write(el + " ")
Next
Console.ReadKey()
End Sub

This example introduces additional methods.


Dim girls(0 To 3) As String

Yet another way to declare an array.

The SetValue() sets a value for a specific index in the array.


names.SetValue("Audrey", 1)
names.SetValue("Ingrid", 3)

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.Copy(names, girls, names.Length)


The Copy() method copies values from the source array to the destination array. The first
parameter is the source array, the second is the destination array. The third parameter is the
length; it specifies the number of elements to copy.

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.

1.16 Functions and Subs Procedures


We use procedures and functions to create modular programs. Visual Basic statements are
grouped in a block enclosed by Sub, Function and matching End statements. The difference
between the two is that functions return values, procedures do not. VB has 2 types of
procedures which are functions and subs.

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

1.16.1 Sub Procedures


A procedure is a block of Visual Basic statements inside Sub, End Sub statements. Procedures do not
return values.
Module Module1
Sub Main()
SimpleProcedure()
End Sub

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

Sub Addition(ByVal k As Integer, ByVal l As Integer)


Console.WriteLine(k + l)
End Sub

In the above example, we pass some values to the Addition() procedure.


Addition(x, y)

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

Function Addition(ByVal k As Integer, ByVal l As Integer)


Return k + l
End Function
End Module
Two values are passed to the function. We add these two values and return the result to the Main()
function.
result = Addition(x, y)

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

Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer


Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End Function
End Module

1.16.3 Exception Handling


An exception is a problem that arises during the execution of a program. An exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.

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

You might also like