0% found this document useful (0 votes)
40 views300 pages

Notes

Uploaded by

yashmya100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views300 pages

Notes

Uploaded by

yashmya100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 300

Section A: unit 1

Introduction to VB: Visual & non-visual programming:


INTRODUCTION VISUAL BASIC is a high level programming language which evolved from the
earlier DOS version called BASIC (Beginners' Allpurpose Symbolic Instruction Code). However,
people prefer to use Microsoft Visual Basic today, as it is a well-developed programming
language and supporting resources are available everywhere. Visual Basic is easy to learn
Programming language. With Visual Basic you can develop Windows based applications and
games. Visual Basic is much easier to learn than other language (like Visual C++), and yet it’s
powerful programming language. Now, there are many versions of VB exist in the market,
the most popular one and still widely used by many VB programmers is none other than
Visual Basic 6 . We also have VB.net, Visual Basic 2005, Visual Basic 2008 , Visual Basic 2010,
Visual Basic 2012 and Visual Basic 2013 . VB2008, VB2010, VB2012 and VB2013 are fully
object oriented programming (OOP) languages. Microsoft Visual Basic development system
version 6.0 is the most productive tool for creating high performance components and
applications. Visual Basic 6.0 offers developers the Ability to create robust applications that
reside on the client or server, cooperate in a distributed n-tier environment. Visual Basic 6.0
is the Rapid Application Development (RAD) tool available either as a stand-alone product or
as a part of the Visual Studio 6.0 suite of tools.

NEED OF VISUAL LANGUAGES OR IMPORTANCE OF VB Visual Basic is regarded as


the third generation event-driven programming language. It was released in 1987. Being the
first visual development tool from Microsoft, it is considered as one of the most powerful
programming languages. As compared to other computer programming languages, such as,
C, C++, it is easy to learn and understand, provided that one has determination and
dedication to do so. Visual basic programming language allows programmers to create
software interface and codes in an easy to use graphical environment. VB is the combination
of different components that are used on forms having specific attributes and actions with
the help of those components. On the one hand it allows programmers to develop widows
based applications rapidly; on the other hand, it helps greatly in accessing data bases, using
ADO while letting the programmers use ActiveX controls and various objects. While it is
intended more to develop applications, it is also useful for
games development for particular or limited purposes, unlike C++ that is more suitable for
developing games. As compared to other languages, Visual basic may be slower though, yet
it is flexible and it can be rightly said that things that are difficult in other languages are
comparatively easier in visual basic programming language. It may also be said that, since it
is one of the most popular programming languages, lots of related books and material and
other resources are available and can be accessed for developing programming skills at
visual basic programming language conveniently. One of the most important things to be
considered with regard to programming in Visual basic is that the structure of VB is designed
in a way that allows programmers to create executable code – Exe files. It enables
programmers to develop programs that can be used as front end to databases. Besides, it’s
with the help of visual basic tools, one can change the abstract ideas into programs or into
the whole software while it allows revising and modifying the programs fittingly. Once you
have advanced your skills at visual basic programming language, you can move to develop
your skills at other languages, such as, VB script. However, it all depends upon your interest
and desire. It must be noted that the sole objective of any computer programming language
is to save time and efforts of the users while making their lives easier. Visual Basic is one of
the most important programming languages having a powerful front-end tool which is able
to achieve simple and complex business requisites in and effective and efficient manner.
EVOLUTION OR HISTORY OF VISUAL BAS

EVOLUTION OR HISTORY OF VISUAL BASIC BASIC (Beginners All Purpose Symbolic Instruction
Code) was developed in 1960’s by Profs Kemeny & Kurtz. 1970’s Bill gates implemented
BASIC in several PCs’. Alan Cooper is considered the father of Visual Basic. In 1987, the then
Director of Applications Software for Coactive Computing Corporation wrote a program
called Ruby (Tripod) that delivered visual programming to the average programmer/user.
Alan Cooper developed VB and sold to Microsoft in 1988. The Visual Basic (VB) system is a
fourth generation programming system which produces much of the code itself as the
programmer designs the interface for his or her application. Microsoft surveys in the late
1990's showed that roughly two-thirds of all business applications programming on PCs was
being done in Visual Basic. Visual Basic 1.0 for Windows was first released on May 20, 1991
at the Windows World convention in Atlanta Georgia
VB version 2.0 for Windows (November 1992) was faster, more powerful and easier to use
than version 1. VB 2 was also available in a freeware student release called the Primer
edition. Visual Basic 3.0 (1993) added tools to access and control databases and Object
Linking and Embedding (OLE) version 2. It came in Standard and Professional versions. A
superset of VB, called Visual Basic for Applications, was released as part of Microsoft Excel 5
and Microsoft Project 4 in 1993. It has since become the internal programming language of
the Microsoft Office family of products, and is available for license by other software
companies. Visual Basic 4 was released in 1995 and supported the new Windows 95 family
of 32-bit operating systems. The Professional Edition could also compile code to run on the
older 16-bit Windows 3.x systems. Visual Basic Scripting Edition (VBScript) was also
announced in 1995. VBScript is used to write embedded code for inclusion in web pages,
although not all web browsers will run VBScript. Visual Basic 5 added, among other things,
the ability to create true executables and to create your own custom controls. It also
supported Microsoft's Active-X technology. Visual Basic 5 was available in Standard
(Learning), Professional and Enterprise Editions. Visual Basic 6 (VB6) was introduced in 1998
and was included as part of a package known as Visual Studio 6.0. VB6 added new
capabilities in the areas of data access, Internet features, controls, component creation,
language features and wizards. To quote Microsoft's web site, «Visual Basic 6.0 features
provide graphical, integrated data access to any ODBC or OLE DB data source, and additional
database-design tools for Oracle and Microsoft SQL Server™-based databases. New Web
development features bring the easy-to-use, component-based programming model of
Visual Basic to the creation of HTML- and Dynamic HTML (DHTML)-based applications. Many
organizations are still using this version today. Version Year New Features VB 1.0 1991 The
interface was barely graphical, using extended ASCII characters to simulate the appearance
of a GUI. VB 2.0 1992 The programming environment was easier to use, and its speed was
improved. VB 3.0 1993 VB3 included a database engine that could read and
INTEGRATED DEVELOPMENT ENVIROMENT
An Integrated Development Environment (IDE) is a software application that provides comprehensive
facilities to computer programmers for software development. An IDE normally consists of a source
code editor, build automation tools and a debugger. WHY VB IS CALLED IDE One of the most
significant changes in Visual Basic 6.0 is the Integrated Development Environment (IDE). IDE is a term
commonly used in the programming World to describe the interface and environment that we use to
create our applications. It is called integrated because we can access virtually all of the development
tools that we need from one screen called an interface. The IDE is also commonly referred to as the
design environment, or the program. Integrated Development Environment (IDE) consists of inbuilt
compiler, debugger, editors, and automation tools for easy development of code. Visual Basic.net
2006 IDE can be accessed by opening a new project. IDE was first introduced with version 5.0 and
Integrated Development Environment of Visual Studio.net 2008 had undergone minor design
changes. VB IDE consists of Solution Explorer, Toolbox, Form, Properties Window, and Menu Bar. In
Visual Studio windows related to a project are combined together and placed at certain locations on
the screen. This type of IDE is known as Multiple Document Interface or MDI. It also having the great
feature called as drag and drop. We can drag & the drop the controls without writing single line of
coding. The below diagram shows the development environment with all the important points
labeled. Many of Visual basic functions work similar to Microsoft word e.g. the Tool Bar and the tool
box is similar to other products on the market which work off a single click then drag the width of the
object required. The Tool Box contains the control you placed on the form window. All of the controls
that appear on the Tool Box controls on the above picture never runs out of controls as soon as you
place one on the form another awaits you on the tool box ready to be placed as needed
Types of variables, Converting variables types, User-defined data
types
Elements of Integrated Development Environmental (IDE). The Visual Basic IDE is made up of
a number of components  Menu Bar  Tool Bar  Project Explorer  Properties window 
Form Layout Window  Toolbox  Form Designer  Object Browser In previous versions of
Visual Basic, the IDE was designed as a Single Document Interface (SDI). In a Single
Document Interface, each window is a free-floating window that is contained within a main
window and can move anywhere on the screen as long as Visual Basic is the current
application. But, in Visual Basic 6.0, the IDE is in a Multiple Document Interface (MDI)
format. In this format, the windows associated with the project will stay within a single
container known as the parent. Code and form-based windows will stay within the main
container form. Visual Basic 6.0 From the desk of Mr. Manjunatha Balluli, Asst. Professor,
Dept. of CS Page 7 of 124 ADVANTAGES OF VB 1. The structure of the Basic programming
language is very simple, particularly as to the executable code. 2. VB is not only a language
but primarily an integrated, interactive development environment (“IDE“). 3. The VB-IDE has
been highly optimized to support rapid application development (“RAD”). It is particularly
easy to Develop Graphical User Interfaces and to connect them to handler functions
provided by the application. 4. The graphical user interface of the VB-IDE provides intuitively
appealing views for the management of the program structure in the large and the various
types of entities (classes, modules, procedures, forms,). 5. It is an Event Driven Programming
which provides complete control to the end user. 6. VB is a first Programmer friendly
language in the world. 7. VB provides a comprehensive interactive and context-sensitive
online help system. 8. When editing program texts the “IntelliSense” technology informs you
in a little popup window about the types of constructs that may be entered at the current
cursor location. 9. Visual Basic 6.0 features provide graphical, integrated data access to any
ODBC or OLE DB data source, and additional database-design tools for Oracle and Microsoft
SQL Server-based databases. 10. New Web development features bring the easy-to-use,
componentbased programming model of Visual Basic to the creation of HTMLand Dynamic
HTML (DHTML)-based applications 11. VB is a component integration language which is
attuned to Microsoft’s Component Object Model (“COM”). 12. COM components can be
written in different languages and then integrated using VB. 13. Interfaces of COM
components can be easily called remotely via Distributed COM (“DCOM”), which makes it
easy to construct distributed applications. 14. COM components can be embedded in /
linked to your application’s user interface and also in/to stored documents (Object Linking
and Embedding “OLE”, “Compound Documents”). 15. There is a wealth of readily available
COM components for many different purposes. 16. Visual Basic is built around the .NET
environment used by all Microsoft Visual languages, so there is very little that can’t be done
in Visual Basic that can be done in other languages (such as C#). Visual Basic 6.0 From the
desk of Mr. Manjunatha Balluli, Asst. Professor, Dept. of CS Page 8 of 124 DISADVANTAGES
OF VB 1. Visual basic is a proprietary programming language written by Microsoft, so
programs written in Visual basic cannot, easily, be transferred to other operating systems. It’s
a platform dependent it only runs on MS Windows operating system. 2. There are some,
fairly minor disadvantages compared with C. C has better declaration of arrays – it’s possible
to initialize an array of structures in C at declaration time; this is impossible in VB.

Visual Development and Event Driven programming.


EVENT DRIVEN PROGRAMMING

Event-driven programming is a programming paradigm in which the flow of program execution is


determined by events - for example a user action such as a mouse click, key press, or a message from
the operating system or another program is known as the Event Driven Programming. VB
programming is also based on Events. An event-driven application is designed to detect events as
they occur, and then deal with them using an appropriate event-handling procedure. When you fire
an event, the code in the event procedure is executed, and then visual basic performs its operations
as per the instructions written in the event procedure code. For example, in the first sample program,
when you click the 'Print' button, the click event is fired, and then the code in the click event
procedure gets executed. The code tells Visual Basic to print a text on the form. So as a result, you
see a text printed on the form.

Example: Write the following code in th

e DblClick event procedure of the form.

Private Sub Form_DblClick()

Print "You have double-clicked"

End Sub

When you double-click on the form,

the DblClick event procedure of the Form object is invoked, and then the code in the DblClick event
procedure is executed. Thus, the code instructs Visual Basic to print a text on the form. Visual Basic
6.0 From the desk of Mr. Manjunatha Balluli, Asst. Professor, Dept. of CS
CHARACTERISTICS AND FEATURES OF VISUAL BASIC Visual Basic (VB)
is a unique computer language---at least it was when it first came out. Now there are many
imitators. VB allows you to quickly and easily develop a bank of visual controls with sliders,
switches and meters or a complex form for a user to fill out. It uses the BASIC language
which is known to most computer programmers, and which can be learned quickly if it is not
already known

The MenuStrip control represents the container for the menu structure.
The MenuStrip control works as the top-level container for the menu
structure. The ToolStripMenuItem class and the ToolStripDropDownMenu
class provide the functionalities to create menu items, sub menus and
drop-down menus.
The following diagram shows adding a MenuStrip control on the form −
Properties of the MenuStrip Control
The following are some of the commonly used properties of the MenuStrip
control −

Sr.N Property & Description


o.

1 CanOverflow
Gets or sets a value indicating whether the MenuStrip supports
overflow functionality.

2
GripStyle
Gets or sets the visibility of the grip used to reposition the control.

3
MdiWindowListItem
Gets or sets the ToolStripMenuItem that is used to display a list of
Multiple-document interface (MDI) child forms.

4
ShowItemToolTips
Gets or sets a value indicating whether ToolTips are shown for the
MenuStrip.

5
Stretch
Gets or sets a value indicating whether the MenuStrip stretches from
end to end in its container.

Events of the MenuStrip Control


The following are some of the commonly used events of the MenuStrip
control −

Sr.No Event & Description


.

1 MenuActivate
Occurs when the user accesses the menu with the keyboard or
mouse.

2
MenuDeactivate
Occurs when the MenuStrip is deactivated.

Example
In this example, let us add menu and sub-menu items.
Take the following steps −
 Drag and drop or double click on a MenuStrip control, to add it
to the form.
 Click the Type Here text to open a text box and enter the
names of the menu items or sub-menu items you want. When
you add a sub-menu, another text box with 'Type Here' text
opens below it.
 Complete the menu structure shown in the diagram above.
 Add a sub menu Exit under the File menu.
 Double-Click the Exit menu created and add the following code
to the Click event of ExitToolStripMenuItem −
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles ExitToolStripMenuItem.Click
End
End Sub
When the above code is executed and run using Start button available at
the Microsoft Visual Studio tool bar, it will show the following window:

Click on the File -> Exit to exit from the application −


Menu Control in VB.Net
A menu, an integral component of a graphical user interface, is
typically positioned on the menu bar and serves as a gateway to a
collection of interconnected commands. It provides users with a list of
options and actions that are grouped together based on their related
functionality.

The MainMenu control serves as a container for structuring the menu


system within a form. This control enables the creation and
organization of menus by utilizing MenuItem objects, which represent
the individual components or parts of a menu.

MainMenu object
To incorporate a menu into a form, you can create a MainMenu object
by employing the MainMenu control. This control acts as the
foundation for building the menu structure within the form, allowing
you to define the hierarchical arrangement and association of menus
and their respective menu items.
To illustrate the process of adding a MainMenu object to a form, the
provided picture demonstrates how to drag and drop a Menustrip
Object onto the form. This visual representation emphasizes the
straightforward nature of incorporating the menu functionality within
your form's design.

After drag the Menustrip on your form you can directly create the
menu items by type a value into the "Type Here" box on the menubar
part of your form. From the following picture you can understand how
to create each menu items on mainmenu Object.
If you need a separator bar , right click on your menu then go to
insert->Separator.
After creating the Menu on the form , you have to double click on
each menu item and write the programs there depends on your
requirements. The following Vb.Net program shows how to show a
messagebox when clicking a menu item.

Full Source VB.NET

Public Class Form1


Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender
As System.Object, ByVal e As System.EventArgs) Handles
MenuItem1ToolStripMenuItem.Click
MsgBox("You are selected MenuItem_1")
End Sub
End Class

Toolbar

Again, if you're a computer user, a toolbar is an item that you've probably


seen many times before. You're probably aware that a toolbar contains
on-screen buttons, icons, menus and other similar elements that
you can use while working with the VBE.

The toolbar that appears in the screenshot above is called the Standard
toolbar. This is the only toolbar that the Visual Basic Editor displays by
default. There are, however, 3 other basic toolbars:

 The Debug toolbar.


 The Edit toolbar.
 The UserForm toolbar.

In addition to the above, the VBE gives you the possibility to


customize the toolbars in several ways.
You can change all of these settings by going to the View menu and
selecting “Toolbars”. The Visual Basic Editor displays a menu with the 4
different toolbars and the option to access the Customize dialog.

The toolbars with a checkmark to their left are those currently displayed
by Excel. You can add or remove a checkmark in order to display or hide a
particular toolbar by clicking on its name. For example, in the screenshot
below, only the Standard toolbar is being displayed.
If you click on “Customize”, the Visual Basic Editor displays the Customize
dialog, which looks as follows:
Using this dialog box, you can control additional aspects regarding the
toolbars that are displayed by the VBE. This includes, for example, the
possibility of controlling the display of the Shortcut Menus toolbar or
adding new toolbars.

You may be wondering what toolbar display set up is commonly


applied by VBA users. In practice, there are different opinions.

 Some advanced VBE users use the default settings.


 However, other advanced VBA users display several toolbars.

You can also add commonly used commands that aren't by default in the
Standard toolbar.
Project Window / Project Explorer

The Project Window, also known as the Project Explorer, is useful for
navigation purposes.

This is the section of the Visual Basic Editor where you'll be able to find
every single Excel workbook that is currently open. This includes add-ins
and hidden workbooks. More particularly, each Excel workbook or add-in
that is open at the moment appears in the Project Explorer as a separate
project.

A project is (basically/simply) a set of modules. If it makes it easier to


understand you can take John Walkenbach's explanation in Excel VBA
Programming for Dummies, who says that a project can be seen as “a
collection of objects arranged as an outline”.

As explained by Walkenbach in Excel 2013 Power Programming with VBA,


each project may have the following nodes:

 A node called “Microsoft Excel Objects” always appears in any


project. This node usually contains 2 types of objects:
o #1: Each worksheet in the relevant Excel workbook. In
other words, each of the worksheets is considered a
separate object.
o #2: The Excel workbook itself, called “ThisWorkbook”.
 The Modules node appears when the project contains VBA modules.
 If the project contains UserForm objects, which are used to create
custom dialog boxes, the Project Explorer displays a node called
“Forms”.
 A project can also contain class modules (modules that define a
class) and, in that case, the Project Window displays a node called
“Class Modules”.
 Finally, if a project has references, there is a node called
“References”.
Let's take a look at how all of this looks in the VBE interface:

In the screenshot below, the only project that appears is the Excel
workbook “Book 1. xlsm”. Within the Microsoft Excel Objects node, you
can see that the Excel workbook has 2 worksheets. Finally, this particular
project contains 1 VBA module and, therefore, the Modules node is visible.
There are, however, no UserForm objects, class modules or references.
Therefore, the Forms, Class Modules and References nodes don't appear.

You can expand or contract the items that appear in the outline by double-
clicking on them or by clicking on the “+” or “-” that appear to the left of
each item, depending on the case.
You can also control whether the items that are displayed in the Project
Window appear in a hierarchical or a non-hierarchical list. You change this
setting by clicking on the Toggle Folders button of the Project Window.

The screenshot above shows items being displayed in a hierarchical list.


When displayed in a non-hierarchical list, the Project Window looks
roughly as follows:

You can also hide or unhide the Project Explorer itself. I explain how to do
this below.
How To Display The Project Window
If you can't see the Project Explorer, you can make the Visual Basic Editor
display it by using any of the following methods:

 Clicking on “Project Explorer” in the View menu.

 Clicking on the Project Explorer icon in the toolbar.

 Using the keyword shortcut “Ctrl + R”.

How To Hide The Project Window


You can hide the Project Explorer by using either of the following methods:
 Clicking on the close button of the Project Window.

 Right-clicking anywhere on the Project Explorer and selecting “Hide”.


Properties Window

The Properties Window displays the properties of the object that is


currently selected in the Project Explorer and allows you to edit those
properties.

Just as with the Project Window, you can hide or unhide the Properties
Window. You're likely to (eventually) work with the Properties Window,
particularly in the context of creating UserForms. If you're just beginning
to use the VBE, you probably won't need this window too much.

In any case, let's take a look at how you can hide or unhide the Properties
Window.

How To Unhide The Properties Window


You can get the Visual Basic Editor to show the Properties Window by
using any of the following methods.
 Clicking on “Properties Window” within the View menu.

 Clicking on the Properties Window icon.

 Using the “F4” keyboard shortcut.


How To Hide The Properties Window
You can get the Visual Basic Editor to hide the Properties Window by doing
either of the following:

 Click on the Close button of the Properties Window.


 Right-click on the Properties Window and select “Hide”.

Component #5: Programming Window / Code


Window / Module Window

As you may expect, the Code Window of the Visual Basic Editor is where
your VBA code appears, and where you can write and edit such
code. At the beginning, though, the Programming Window is empty as in
the screenshot above.

There is a Code Window for every single object in a project. You can
access the window of a particular object by going to the Project Explorer
and doing any of the following:

 Double clicking on the object. The main exception to this rule are
UserForms. If you double-click on a UserForm, the Visual Basic Editor
displays the UserForm in Design view, a topic I'll cover in future
tutorials.

 Selecting the object and, then, clicking on “Code” in the View menu.

 Selecting the object and clicking on the View Code icon that appears
at the top of the Project Explorer.
 Right-clicking on the object and selecting “View Code”.

 Using the keyboard shortcut “F7”.


Immediate Window
The main purpose of the Immediate Window is to help you noticing
errors, checking or debugging VBA code.

The Immediate Window is, by default, hidden. However, as with most of


the other windows, you can unhide it. Let' take a look at how you can do
both the hiding and the un-hiding:

How To Unhide The Immediate Window


You can unhide the Immediate Window by doing either of the following:

 Clicking on “Immediate Window” in the View menu.

 Using the “Ctrl + G” keyboard shortcut.

However, as explained in Excel VBA Programming for Dummies, if you're


just getting started with the VBE “this window won't be all that useful”.
Therefore, if you're just beginning to work with macros and Visual Basic
for Applications, you probably don't need to display the Immediate
Window.
If you're a more advanced user, you'll probably want to have the Visual
Basic Editor show the Immediate Window, since this can be very useful.

How To Hide The Immediate Window


You can hide the Immediate Window using either of the following
methods:

 Click the Close button.

 Right-click on the Immediate Window and select “Hide”.

You already know that:

 The VBE allows you to customize several aspects.


 On your way to becoming a macro and VBA expert you'll probably
spend a significant amount of time working with the Visual Basic
Editor.

Therefore, its important to have a basic idea of…

How To Customize The Visual Basic


Editor
If you want to customize the Visual Basic Editor, the first thing you'll want
to do is open the Options dialog. To do this, go to the Tools menu and
click on “Options”.
The Options dialog looks roughly as follows.

As you can see, there are plenty of settings you can modify. In most
cases, you can enable or disable an option by clicking on the blank box to
the left of it. If there is a checkmark, the option is enabled. If the box is
empty, the option is not enabled.
In the screenshot above, the only option that is not enabled is “Require
Variable Declaration”.

For the moment, let's take a look at some of the most common
suggestions made by Excel experts. The following sections go separately
through each of the 4 tabs in the Options dialog:

 Editor.
 Editor Format.
 General.
 Docking.
Editor Tab
The Editor tab is where you can determine the settings for the Code
Window and Project Window. Let's take a look at the main settings of
this tab.
Code Settings
Setting #1: Auto Syntax Check.

This option allows you to determine what happens when you make a
syntax error while entering VBA code. There are 2 options:

 If Auto Syntax Check is enabled, a dialog box pops up as soon as the


VBE discovers that you've made a syntax error. This dialog box gives
you a rough idea of what mistake you've made. Additionally, the
Visual Basic Editor highlights the syntax error by using a different
font color (usually red).

Let's take a look at the VBA code for a very simple macro that deletes
rows when some of the cells are blank. The second statement of this
macro is
“Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete”. If, for
example, I press the Enter key after “Selection.”, the Visual Basic
Editor gives me the following warning signs:
 If Auto Syntax Check is disabled, the Visual Basic Editor displays
syntax errors in a different font color (usually red). Under this setting,
no dialog boxes pop on your screen.

In the case of the syntax error used as an example above, the VBE
looks roughly as follows:
Section B: unit -ii
Basics of Programming: Variables: Declaring variables, Types of variables
Variables in Visual Basic
You often have to store values when you perform calculations with Visual Basic.
For example, you might want to calculate several values, compare them, and
perform different operations on them, depending on the result of the
comparison. You have to retain the values if you want to compare them.
Usage
Visual Basic, just like most programming languages, uses variables for storing
values. A variable has a name (the word that you use to refer to the value that
the variable contains). A variable also has a data type (which determines the
kind of data that the variable can store). A variable can represent an array if it
has to store an indexed set of closely related data items.
Local type inference enables you to declare variables without explicitly stating a
data type. Instead, the compiler infers the type of the variable from the type of
the initialization expression. For more information, see Local Type
Inference and Option Infer Statement.
Assigning Values
You use assignment statements to perform calculations and assign the result to
a variable, as the following example shows.
VBCopy
' The following statement assigns the value 10 to the variable.
applesSold = 10
' The following statement increments the variable.
applesSold = applesSold + 1
' The variable now holds the value 11.
Note
The equal sign (=) in this example is an assignment operator, not an equality
operator. The value is being assigned to the variable applesSold.
For more information, see How to: Move Data Into and Out of a Variable.
Variables and Properties
Like a variable, a property represents a value that you can access. However, it is
more complex than a variable. A property uses code blocks that control how to
set and retrieve its value. For more information, see Differences Between
Properties and Variables in Visual Basic.
Declaration Levels
Local and Member Variables
A local variable is one that is declared within a procedure. A member variable is
a member of a Visual Basic type; it is declared at module level, inside a class,
structure, or module, but not within any procedure internal to that class,
structure, or module.
Shared and Instance Variables
In a class or structure, the category of a member variable depends on whether
or not it is shared. If it is declared with the Shared keyword, it is a shared
variable, and it exists in a single copy shared among all instances of the class or
structure.
Otherwise it is an instance variable, and a separate copy of it is created for each
instance of the class or structure. A given copy of an instance variable is
available only to the instance of the class or structure in which it was created. It
is independent of a copy of the instance variable in any other instance of the
class or structure.
Declaring Data Type
The As clause in the declaration statement allows you to define the data type
or object type of the variable you are declaring. You can specify any of the
following types for a variable:
 An elementary data type, such as Boolean, Long, or Decimal
 A composite data type, such as an array or structure
 An object type, or class, defined either in your application or in another
application
 A .NET Framework class, such as Label or TextBox
 An interface type, such as IComparable or IDisposable
You can declare several variables in one statement without having to repeat the
data type. In the following statements, the variables i, j, and k are declared as
type Integer, l and m as Long, and x and y as Single:
VBCopy
Dim i, j, k As Integer
' All three variables in the preceding statement are declared as Integer.
Dim l, m As Long, x, y As Single
' In the preceding statement, l and m are Long, x and y are Single.
For more information on data types, see Data Types. For more information on
objects, see Objects and Classes and Programming with Components.
Local Type Inference
Type inference is used to determine the data types of local variables declared
without an As clause. The compiler infers the type of the variable from the type
of the initialization expression. This enables you to declare variables without
explicitly stating a type. In the following example, both num1 and num2 are
strongly typed as integers.
VBCopy
Public Sub inferenceExample()

' Using explicit typing.


Dim num1 As Integer = 3

' Using local type inference.


Dim num2 = 3

End Sub
If you want to use local type inference, Option Infer must be set to On. For
more information, see Local Type Inference and Option Infer Statement.
Characteristics of Declared Variables
The lifetime of a variable is the period of time during which it is available for
use. In general, a variable exists as long as the element that declares it (such as
a procedure or class) continues to exist. If the variable does not need to
continue existing beyond the lifetime of its containing element, you do not
need to do anything special in the declaration. If the variable needs to continue
to exist longer than its containing element, you can include
the Static or Shared keyword in its Dim statement. For more information,
see Lifetime in Visual Basic.
The scope of a variable is the set of all code that can refer to it without
qualifying its name. A variable's scope is determined by where it is declared.
Code located in a given region can use the variables defined in that region
without having to qualify their names. For more information, see Scope in
Visual Basic.
A variable's access level is the extent of code that has permission to access it.
This is determined by the access modifier (such as Public or Private) that you
use in the Dim statement. For more information, see Access levels in Visual
Basic.

You create a variable with a Dim Statement.


To create a new variable
1. Declare the variable in a Dim statement.
VBCopy
Dim newCustomer
2. Include specifications for the variable's characteristics, such
as Private, Static, Shadows, or WithEvents. For more information,
see Declared Element Characteristics.
VBCopy
Public Static newCustomer
You do not need the Dim keyword if you use other keywords in the declaration.
3. Follow the specifications with the variable's name, which must follow
Visual Basic rules and conventions. For more information, see Declared
Element Names.
VBCopy
Public Static newCustomer
4. Follow the name with the As clause to specify the variable's data type.
VBCopy
Public Static newCustomer As Customer
If you do not specify the data type, it uses the default: Object.
5. Follow the As clause with an equal sign (=) and follow the equal sign with
the variable's initial value.
Visual Basic assigns the specified value to the variable every time it runs
the Dim statement. If you do not specify an initial value, Visual Basic assigns the
default initial value for the variable's data type when it first enters the code
that contains the Dim statement.
If the variable is a reference type, you can create an instance of its class by
including the New Operator keyword in the As clause. If you do not use New,
the initial value of the variable is Nothing.
VBCopy
Public Static newCustomer As New Customer
Every declared element has a name, also called an identifier, which is what the
code uses to refer to it.
Rules
An element name in Visual Basic must observe the following rules:
 It must begin with an alphabetic character or an underscore (_).
 It must only contain alphabetic characters, decimal digits, and
underscores.
 It must contain at least one alphabetic character or decimal digit if it
begins with an underscore.
 It must not be more than 1023 characters long.
The length limit of 1023 characters also applies to the entire string of a fully
qualified name, such
as outerNamespace.middleNamespace.innerNamespace.thisClass.thisElement.
The following example shows some valid element names.
aB123__45
_567
The following example shows some invalid element names. The first contains
only an underscore, the second begins with a decimal digit, and the third
contains an invalid character ($).
' Three INVALID element names
Name Length Guidelines
As a practical matter, your name should be as short as possible while still clearly
identifying the nature of the element. This improves the readability of your
code and reduces line length and source-file size.
On the other hand, your name should not be so short that it does not
adequately describe what the element represents and how your code uses it.
This is important for the readability of your code. If somebody else is trying to
understand it, or if you yourself are looking at it a long time after you wrote it,
suitable element names can save a considerable amount of time.
Escaped Names
Generally, an element name must not match any of the keywords reserved by
Visual Basic, such as Case or Friend. However, you can define an escaped name,
which is enclosed by brackets ([ ]). An escaped name can match any Visual Basic
keyword, since the brackets remove any ambiguity. You also use the brackets
when you refer to the name later in your code.
In general, you should use escaped names only when:
 Your code has migrated from a previous version of Visual Basic that did
not reserve the keyword being used as a name; or
 You are working with code written in another language in which the
given keyword is not reserved.
Otherwise, you should consider renaming the element if its name conflicts with
a keyword. The integrated development environment (IDE) provides an easy
way to do this. For more information, see Refactoring.
Case Sensitivity in Names
Element names in Visual Basic are case-insensitive. This means that when the
compiler compares two names that differ in alphabetic case only, it interprets
them as the same name. For example, it considers ABC and abc to refer to the
same declared element.
However, the common language runtime (CLR) uses case-sensitive binding.
Therefore, when you produce an assembly or a DLL and make it available to
other assemblies, your names are no longer case-insensitive. For example, if
you define a class with an element called ABC, and other assemblies make use
of your class through the common language runtime, they must refer to the
element as ABC. If you subsequently recompile your class and change the
element's name to abc, the other assemblies using your class could no longer
access that element. Therefore, when you release an updated version of an
assembly, you should not change the alphabetic case of any public elements.
Names and Locales
Comparison of names is independent of locale. If two names match in one
locale, they are guaranteed to match in all locales.

Show 3 more
When your code refers to a declared element, the Visual Basic compiler
matches the name in your reference to the appropriate declaration of that
name. If more than one element is declared with the same name, you can
control which of those elements is to be referenced by qualifying its name.
The compiler attempts to match a name reference to a name declaration with
the narrowest scope. This means it starts with the code making the reference
and works outward through successive levels of containing elements.
The following example shows references to two variables with the same name.
The example declares two variables, each named totalCount, at different levels
of scope in module container. When the
procedure showCount displays totalCount without qualification, the Visual
Basic compiler resolves the reference to the declaration with the narrowest
scope, namely the local declaration inside showCount. When it
qualifies totalCount with the containing module container, the compiler
resolves the reference to the declaration with the broader scope.
VBCopy
' Assume these two modules are both in the same assembly.
Module container
Public totalCount As Integer = 1
Public Sub showCount()
Dim totalCount As Integer = 6000
' The following statement displays the local totalCount (6000).
MsgBox("Unqualified totalCount is " & CStr(totalCount))
' The following statement displays the module's totalCount (1).
MsgBox("container.totalCount is " & CStr(container.totalCount))
End Sub
End Module
Module callingModule
Public Sub displayCount()
container.showCount()
' The following statement displays the containing module's totalCount (1).
MsgBox("container.totalCount is " & CStr(container.totalCount))
End Sub
End Module
Qualifying an Element Name
If you want to override this search process and specify a name declared in a
broader scope, you must qualify the name with the containing element of the
broader scope. In some cases, you might also have to qualify the containing
element.
Qualifying a name means preceding it in your source statement with
information that identifies where the target element is defined. This
information is called a qualification string. It can include one or more
namespaces and a module, class, or structure.
The qualification string should unambiguously specify the module, class, or
structure containing the target element. The container might in turn be located
in another containing element, usually a namespace. You might need to include
several containing elements in the qualification string.
To access a declared element by qualifying its name
1. Determine the location in which the element has been defined. This
might include a namespace, or even a hierarchy of namespaces. Within
the lowest-level namespace, the element must be contained in a module,
class, or structure.
VBCopy
' Assume the following hierarchy exists outside your code.
Namespace outerSpace
Namespace innerSpace
Module holdsTotals
Public Structure totals
Public thisTotal As Integer
Public Shared grandTotal As Long
End Structure
End Module
End Namespace
End Namespace
2. Determine a qualification path based on the target element's location.
Start with the highest-level namespace, proceed to the lowest-level
namespace, and end with the module, class, or structure containing the
target element. Each element in the path must contain the element that
follows it.
outerSpace → innerSpace → holdsTotals → totals
3. Prepare the qualification string for the target element. Place a period (.)
after every element in the path. Your application must have access to
every element in your qualification string.
VBCopy
outerSpace.innerSpace.holdsTotals.totals.
4. Write the expression or assignment statement referring to the target
element in the normal way.
VBCopy
grandTotal = 9000
5. Precede the target element name with the qualification string. The name
should immediately follow the period (.) that follows the module, class,
or structure that contains the element.
VBCopy
' Assume the following module is part of your code.
Module accessGrandTotal
Public Sub setGrandTotal()
outerSpace.innerSpace.holdsTotals.totals.grandTotal = 9000
End Sub
End Module
6. The compiler uses the qualification string to find a clear, unambiguous
declaration to which it can match the target element reference.
You might also have to qualify a name reference if your application has access
to more than one programming element that has the same name. For example,
the System.Windows.Forms and System.Web.UI.WebControls namespaces both
contain a Label class
(System.Windows.Forms.Label and System.Web.UI.WebControls.Label). If your
application uses both, or if it defines its own Label class, you must distinguish
the different Label objects. Include the namespace or import alias in the
variable declaration. The following example uses the import alias.
VBCopy
' The following statement must precede all your declarations.
Imports win = System.Windows.Forms, web = System.Web.UI.WebControls
' The following statement references the Windows.Forms.Label class.
Dim winLabel As New win.Label()
Members of Other Containing Elements
When you use a nonshared member of another class or structure, you must
first qualify the member name with a variable or expression that points to an
instance of the class or structure. In the following example, demoClass is an
instance of a class named class1.
VBCopy
Dim demoClass As class1 = New class1()
demoClass.someSub[(argumentlist)]
You cannot use the class name itself to qualify a member that is not Shared.
You must first create an instance in an object variable (in this case demoClass)
and then reference it by the variable name.
If a class or structure has a Shared member, you can qualify that member either
with the class or structure name or with a variable or expression that points to
an instance.
A module does not have any separate instances, and all its members
are Shared by default. Therefore, you qualify a module member with the
module name.
The following example shows qualified references to module member
procedures. The example declares two Sub procedures, both named perform,
in different modules in a project. Each one can be specified without
qualification within its own module but must be qualified if referenced from
anywhere else. Because the final reference in module3 does not
qualify perform, the compiler cannot resolve that reference.
VBCopy
' Assume these three modules are all in the same assembly.
Module module1
Public Sub perform()
MsgBox("module1.perform() now returning")
End Sub
End Module
Module module2
Public Sub perform()
MsgBox("module2.perform() now returning")
End Sub
Public Sub doSomething()
' The following statement calls perform in module2, the active module.
perform()
' The following statement calls perform in module1.
module1.perform()
End Sub
End Module
Module module3
Public Sub callPerform()
' The following statement calls perform in module1.
module1.perform()
' The following statement makes an unresolvable name reference
' and therefore generates a COMPILER ERROR.
perform() ' INVALID statement
End Sub
End Module
References to Projects
To use Public elements defined in another project, you must first set
a reference to that project's assembly or type library. To set a reference,
click Add Reference on the Project menu, or use the -reference (Visual
Basic) command-line compiler option.
For example, you can use the XML object model of the .NET Framework. If you
set a reference to the System.Xml namespace, you can declare and use any of
its classes, such as XmlDocument. The following example uses XmlDocument.
VBCopy
' Assume this project has a reference to System.Xml
' The following statement creates xDoc as an XML document object.
Dim xDoc As System.Xml.XmlDocument
Importing Containing Elements
You can use the Imports Statement (.NET Namespace and Type) to import the
namespaces that contain the modules or classes that you want to use. This
enables you to refer to the elements defined in an imported namespace
without fully qualifying their names. The following example rewrites the
previous example to import the System.Xml namespace.
VBCopy
' Assume this project has a reference to System.Xml
' The following statement must precede all your declarations.
Imports System.Xml
' The following statement creates xDoc as an XML document object.
Dim xDoc As XmlDocument
In addition, the Imports statement can define an import alias for each imported
namespace. This can make the source code shorter and easier to read. The
following example rewrites the previous example to use xD as an alias for
the System.Xml namespace.
VBCopy
' Assume this project has a reference to System.Xml
' The following statement must precede all your declarations.
Imports xD = System.Xml
' The following statement creates xDoc as an XML document object.
Dim xDoc As xD.XmlDocument
The Imports statement does not make elements from other projects available
to your application. That is, it does not take the place of setting a reference.
Importing a namespace just removes the requirement to qualify the names
defined in that namespace.
You can also use the Imports statement to import modules, classes, structures,
and enumerations. You can then use the members of such imported elements
without qualification. However, you must always qualify nonshared members of
classes and structures with a variable or expression that evaluates to an
instance of the class or structure.
What is Operator in VB.Net?
An Operator in VB.Net 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. We will discuss them in this tutorial.
rithmetic Operators in VB.Net
You can use arithmetic operators to perform various mathematical operations
in VB.NET. Arithmetic operators in VB.Net include:
Arithmetic
Description
Operator

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

known as the modulus operator. It returns the remainder after


MOD
division.

Example of VB.Net Arithmetic Operator


Here is an example of VB.Net arithmetic operator:
Step 1) Create a new console application. To know this, visit our previous
tutorial on Data Types and Variables.
Step 2) Add the following code:
Module Module1

Sub Main()
Dim var_w As Integer = 11
Dim var_x As Integer = 5
Dim var_q As Integer = 2
Dim var_y As Integer
Dim var_z As Single

var_y = var_w + var_z


Console.WriteLine(" Result of 11 + 5 is {0} ", var_y)

var_y = var_w - var_x


Console.WriteLine(" Result of 11 - 5 is {0} ", var_y)

var_y = var_w * var_x


Console.WriteLine(" Result of 11 * 5 is {0} ", var_y)

var_z = var_w / var_x


Console.WriteLine(" Result of 11 / 5 is {0}", var_z)

var_y = var_w \ var_x


Console.WriteLine(" Result of 11 \ 5 is {0}", var_y)
var_y = var_w Mod var_x
Console.WriteLine(" Result of 11 MOD 5 is {0}", var_y)

var_y = var_x ^ var_x


Console.WriteLine(" Result of 5 ^ 5 is {0}", var_y)
Console.ReadLine()

End Sub

End Module
Step 3) Click the Start button to execute the code. You should get the following
window:

Comparison Operators in VB.Net


Comparison operators are used for making comparisons between variables.
Comparison operators in VB.Net include the following:
Comparison
Description
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.
Example of VB.Net Comparison Operator
Let us demonstrate an example of VB.Net comparison operator:
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:
Module Module1

Sub Main()
Dim x As Integer = 11
Dim y As Integer = 5
If (x = y) Then
Console.WriteLine("11=5 is True")
Else
Console.WriteLine(" 11=5 is False")
End If

If (x < y) Then
Console.WriteLine(" 11<5 is True")
Else
Console.WriteLine(" 11<5 is False")
End If

If (x > y) Then
Console.WriteLine(" 11>5 is True")
Else
Console.WriteLine(" 11>5 is False")
End If

x=3
y=7
If (x <= y) Then
Console.WriteLine(" 3<=7 is True")
End If
If (y >= x) Then
Console.WriteLine(" 7>=3 is True")
End If
Console.ReadLine()

End Sub
End Module
Step 3) Click the Start button from the toolbar to run the code. You should get
the following window:

Logical Operators in VB.Net


Logical operators help us in making logical decisions. Logical Operators in
VB.Net are:
Logical
Description
Operator

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

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

The logical/bitwise NOT. To reverse operand’s logical state. If true, the


Not
condition becomes False and vice versa.

bitwise Logical Exclusive OR operator. Returns False if expressions are all


Xor
True or False. Otherwise, it returns True.

It is also known as the logical AND operator. Only works with Boolean data
AndAlso
by performing short-circuiting.

It is also known as the logical OR operator. Only works with Boolean data
OrElse
by performing short-circuiting.

IsFalse Determines whether expression evaluates to False.

IsTrue Determines whether expression evaluates to True.


Example of VB.Net Logical Operator
Let us demonstrate how to use logical 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:
Module Module1

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
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
End Module
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:
Bit Shift Operators in VB.Net
These operators are used for performing shift operations on binary values.
Bit Shift
Description
Operatiors

Known as the Bitwise AND Operator. It copies a bit to result if it is


And
found in both operands.

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


Or
operand.

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

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


Not
operator that ‘flips’ the bits.
Bit Shift Operator Example in VB.Net
Let us demonstrate bit shift 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:
Module Module1
Sub Main()

Dim w As Integer = 50
Dim x As Integer = 11
Dim y As Integer = 0
y = w And x
Console.WriteLine("y = w And x is {0}", y)
y = w Or x

Console.WriteLine("y = w Or x is {0}", y)
y = w Xor x

Console.WriteLine("y = w Xor x is {0}", y)


y = Not w

Console.WriteLine("y = Not w is {0}", y)


Console.ReadLine()

End Sub
End Module
Step 3) Run the code by clicking the Start button. You should get the following
window:

Here is a screenshot of the code:


Naming Guidelines
When you define two or more programming elements that have the same
name, a name ambiguity can result when the compiler attempts to resolve a
reference to that name. If more than one definition is in scope, or if no
definition is in scope, the reference is irresolvable. For an example, see
"Qualified Reference Example" on this Help page.
You can avoid name ambiguity by giving all your elements unique names. Then
you can make reference to any element without having to qualify its name with
a namespace, module, or class. You also reduce the chances of accidentally
referring to the wrong element.
Shadowing
When two programming elements share the same name, one of them can hide,
or shadow, the other one. A shadowed element is not available for reference;
instead, when your code uses the shadowed element name, the Visual Basic
compiler resolves it to the shadowing element. For a more detailed explanation
with examples, see Shadowing in Visual Basic.

STRUCTURE OF A VISUAL BASIC APPLICATION To run Visual Basic program, select, Start ->
Programs ->Microsoft Visual Basic 6.0 New Project dialog. The New Project dialog allows the
programmer to choose what type of Visual Basic program to create. Standard EXE, which is
highlighted by default, allows the programmer to create a standard executable. Each type
listed in) describes a group of related files called a Project. Project (VBP) Project is a program
designed to user application that may be simple (like calculator program) or complex (like
word program). The project types listed in are the “Visual” in Visual Basic, because they
contain predefined features for designing Windows programs. The project is a collection of
files that makes the user program. They may consist of form, modules, active x controls. The
new project dialog contains three tabs • New: creating new project. • Existing: opening an
existing project. • Recent: opening a project that has been previously loaded into the IDE.
Application (Project) is made up of:
1. Forms - Windows that you create for user interface
2. Controls - Graphical features drawn on forms to allow user interaction (text boxes, labels,
scroll bars, command buttons, etc.) (Forms and Controls are objects.)
3. Properties - Every characteristic of a form or control is specified by a property. Example
properties include names, captions, size, color,
Steps in Developing Application
There are three primary steps involved in building a Visual Basic application:
1. Draw the user interface
2. Assign properties to controls
3. Attach code to controls We’ll look at each step.
Drawing the User Interface and Setting Properties  Visual Basic operates in
three modes. Design mode - used to build application Run mode - used to run
the application Break mode - application halted and debugger is available We
focus here on the design mode. Six windows appear when you start Visual
Basic. The Main Window consists of the title bar, menu bar, and toolbar. The
title bar indicates the project name, the current Visual Basic operating mode,
and the current form. The menu bar has drop-down menus from which you
control the operation of the Visual Basic environment. The toolbar has buttons
that provide shortcuts to some of the menu options. The main window also
shows the location of the current form relative to the upper left corner of the
screen (measured in twips) and the width and length of the current form
User-defined data types, Forcing variable declaration, Scope & lifetime of
variables. Constants:
PROJECT EXPLORER WINDOW: The window titled Project-Project1 is called the Project
Explorer and contains the project files. The project explorer window’s tool bar contains three
buttons, namely view code, view object and toggle folders. When pressed, the view code
button displays a window for writing Visual Basic code. View object, when pressed, displays
the form. Double-clicking form1 (form1) also displays the form. The toggle folders button
toggles (i.e., alternately hides or shows) the forms folder. The forms folder contains a listing
of all forms in the current project. To show the Project Explorer window press View> Project
Explorer window icon FORM LAYOUT WINDOW:

The Form Layout window specifies a form’s position on the screen at runtime. The Form
Layout window consists of an image representing the screen and the form’s relative position
on the screen. With the mouse pointer positioned over the form image, drag the form to a
new location. As mentioned, the user interface is ‘drawn’ in the form window. There are two
ways to place controls on a form: 1. Double-click the tool in the toolbox and it is created with
a default size on the form. You can then move it or resize it. 2. Click the tool in the toolbox,
then move the mouse pointer to the form window. The cursor changes to a crosshair. Place
the crosshair at the upper left corner of where you want the control to be, press the left
mouse button and hold it down while dragging the cursor toward the lower right
VB.NET Variable and Constant
In VB.NET, a variable is used to hold the value that can be used further
in the programming. In this section, we will learn how to declare and
initialize a variable and a constant.

What is a Variable?
A variable is a simple name used to store the value of a specific data type
in computer memory. In VB.NET, each variable has a particular data type
that determines the size, range, and fixed space in computer memory.
With the help of variable, we can perform several operations and
manipulate data values in any programming language.

VB.NET Variables Declaration


The declaration of a variable is simple that requires a variable name and
data type followed by a Dim. A Dim is used in Class, Module, structure,
Sub, procedure.

Syntax:

Backward Skip 10sPlay VideoForward Skip 10s

1. Dim [Variable_Name] As [Defined Data Type]

Name Descriptions

Dim It is used to declare and allocate the space for one or more variable
memory.

Variable_Na It defines the name of the variable to store the values.


me

As It is a keyword that allows you to define the data type in the declara
statement.

Data Type It defines a data type that allows variables to store data types such
Char, String, Integer, Decimal, Long, etc.

Value Assign a value to the variable.

There are some valid declarations of variables along with their data type
definition, as shown below:

1. Dim Roll_no As Integer


2. Dim Emp_name As String
3. Dim Salary As Double
4. Dim Emp_id, Stud_id As Integer
5. Dim result_status As Boolean

Further, if we want to declare more than one variable in the same line,
we must separate each variable with a comma.

Syntax

1. Dim Variable_name1 As DataType1, variable_name2 As DataType2,


Variable_name3 As DataType3

Note: The statements given below is also used to declare the variable with their data
type:

1. Static name As String


2. Public bill As Decimal = 0

VB.NET Variable Initialization


After the declaration of a variable, we must assign a value to the variable.
The following syntax describes the initialization of a variable:

Syntax:

1. Variable_name = value

For example:

1. Dim Roll_no As Integer 'declaration of Roll_no


2. Roll_no = 101 'initialization of Roll_no
3.
4. Initialize the Emp_name
5. Dim Emp_name As String
6. Emp_name = "David" 'Here Emp_name variable assigned a value of
David
7.
8. Initialize a Boolean variable
9. Dim status As Boolean 'Boolean value can be True or False.
10. status = True 'Initialize status value to True
We can also initialize a variable at the time of declaration:

1. Dim Roll_no As Integer = 101


2. Dim Emp_name As String = " Stephen Robert "

Let's create a program to use different types of variable declaration and


initialization in VB.NET.

Variable1.vb

1. Imports System
2. Module Variable1
3. Sub Main()
4. 'declaration of intData as Integer
5. Dim intData As Integer
6. 'declaration of charData as Char
7. Dim CharData As Char
8. 'declaration of strData as String
9. Dim strData As String
10. 'declaration of dblData as Double
11. Dim dblData As Double
12. 'declaration of single_data as Single
13. Dim single_data As Single
14. 'Initialization of intData
15. intData = 10
16. 'Initialization of CharData
17. CharData = "A"
18. 'Initialization of strData
19. strData = " VB.NET is a Programming Language."
20. dblData = 4567.676
21. 'Initialization of dblData
22. 'Initialization of single_data
23. single_data = 23.08
24.
25. Console.WriteLine(" Value of intData is: {0}", intData)
26. Console.WriteLine(" Value of CharData is: {0}", CharData
)
27. Console.WriteLine(" Value of strData is: {0}", strData)
28. Console.WriteLine(" Value of dblData is: {0}", dblData)
29. Console.WriteLine(" Value of single_data is: {0}", single_
data)
30.
31. Console.WriteLine("press any key to exit...")
32. Console.ReadKey()
33. End Sub
34.
35. End Module

Output:

Value of intData is: 10


Value of CharData is: A
Value of strData is: VB.NET is a Programming Language.
Value of dblData is: 4567.676
Value of single_data is: 23.08
press any key to exit...

Getting Values from the User in VB.NET


In VB.NET, the Console class provides the Readline() function in the
System namespace. It is used to take input from the user and assign a
value to a variable. For example:

1. Dim name As String


2. name = Console.ReadLine()
3. Or name = Console.ReadLine

Let's create a program that takes input from the user.

User_Data.vb

1. Imports System
2. Module User_Data
3. Sub Main()
4. Dim num As Integer
5. Dim age As Double
6. Dim name As String
7. Console.WriteLine("Enter your favourite number")
8. ' Console.ReadLine or Console.ReadLine() takes value from the
user
9. num = Console.ReadLine
10. Console.WriteLine(" Enter Your Good name")
11. 'Read string data from the user
12. name = Console.ReadLine
13. Console.WriteLine(" Enter your Age")
14. age = Console.ReadLine
15. Console.WriteLine(" You have entered {0}", num)
16. Console.WriteLine(" You have entered {0}", name)
17. Console.WriteLine(" You have entered {0}", age)
18. Console.ReadKey()
19.
20. End Sub
21. End Module

Output:

Enter your favourite number


7
Enter Your Good name
Alexander
Enter your Age
27.5
You have entered 7
You have entered Alexander
You have entered 27.5

Note: Console.Read and Console.ReadKey() function is used to read a single character


from the user.

Lvalues and Rvalues in VB.NET


There are two ways to express the expression value:

Lvalue: It is an lvalue expression that refers to a memory location for


storing the address of a variable. An lvalue is a variable that can appear to
the left or right of the assignment operator to hold values. Furthermore, in
comparison to or swapping the variables' values, we can also define the
variable on both sides (left or right-side) of the assignment operator.

Example:

1. Dim num As Integer


2. Num = 5
3. Or
4. Dim num As Integer = 5
But when we write the following statement, it generates a compile-time
error because it is not a valid statement.

1. Dim x As Integer
2. 10 = x

Rvalue: It is an rvalue expression that is used to store a value in some


address of memory. An rvalue can appear only on the right- hand side
because it is a value of the variable that defines on the right-hand side.

1. Dim name As String


2. Name = "Peter" // rvalue define at right side of the assignment oper
ator.

VB.NET Constants
As the name suggests, the name constant refers to a fixed value that
cannot be changed during the execution of a program. It is also known
as literals. These constants can be of any data type, such as Integer,
Double, String, Decimal, Single, character, enum, etc.

Declaration of Constants
In VB.NET, const is a keyword that is used to declare a variable as
constant. The Const statement can be used with module, structure,
procedure, form, and class.

Syntax:

1. Const constname As datatype = value

Item Descriptions
Name

Const It is a Const keyword to declare a variable as constant.

Constna It defines the name of the constant variable to store the values.
me

As It is a keyword that allows you to define the data type in the declara
statement.
Data It defines a data type that allows variables to store data types such as C
Type String, Integer, Decimal, Long, etc.

Value Assign a value to the variable as constant.

Further, if we want to declare more than one variable in the same line,
we must separate each variable with a comma, as shown below. The
Syntax for defining the multiple variables as constant is:

1. Dim Variable_name1 As DataType1, variable_name2 As DataType2,


Variable_name3 As DataType3

Note: The statements given below are also used to declare the variable with their data
type:

1. Const num As Integer = 10


2. Static name As String
3. Public Const name As String = "JavaTpoint"
4. Private Const PI As Double = 3.14

Example of Const keyword

Const1.vb

1. Module Const1
2. Sub main()
3. 'declaration and initialization of Constant variable using Const k
eywords
4. Const intData As Integer = 20
5. Const name As String = "JavaTpoint"
6. Const topic As String = "VB.NET"
7. Const PI = 3.14
8. Dim radius, area As Integer
9.
10. Console.WriteLine(" Constant integer is {0}", intData)
11. Console.WriteLine(" You have entered {0}", name)
12. Console.WriteLine(" Your Topic is {0}", topic)
13. Console.WriteLine("Enter the Radius")
14. radius = Console.ReadLine()
15. area = PI * radius * radius
16. Console.WriteLine(" Area of Circle is {0}", area)
17. Console.ReadKey()
18.
19. End Sub
20. End Module

Output:

Constant integer is 20
You have entered JavaTpoint
Your Topic is VB.NET
Enter the Radius
7
Area of Circle is 154

Scope of Variable in VB.NET


The scope of a variable determines the accessible range of a defined
variable at the time of declaration in any block, module, and class. You
can access it if the variable is in a particular region or scope in the same
block. And if the variable goes beyond the region, its scope expires.

The following are the methods to represent the scope of a variable in


VB.NET.

1. Procedure Scope
2. Module Scope
3. Public Scope

Procedure (local) scope


A local variable is a type of variable defined within a procedure scope,
block, or function. It is available with a code inside the procedure, and it
can be declared using the Dim or static statement. These variables are
not accessible from outside of the local method. However, the local
variable can be easily accessed by the nested programming function in
the same method.

1. Dim X As Integer

Local variables exist until the procedure in which they are declared is
executed. Once a procedure is executed, the values of its local variables
will be lost, and the resources used by these variables will be released.
And when the block is executed again, all the local variables are
rearranged.
Let's create a program that displays the local scope of a variable within a
function.

Local_Scope.vb

1. Imports System
2. Module Local_scope
3. Sub Main()
4. Console.WriteLine(" Scope of local varibale within a function")
5. local() ' call local() and local() function without any object refere
nce
6. local2()
7. Console.WriteLine("press any key to exit...")
8. Console.ReadKey()
9. End Sub
10. Sub local()
11. Dim X As Integer
12. ' declaration of local variable
13. X = 50
14. Console.WriteLine(" Value of Local value X is {0}", X)
15.
16. End Sub
17. Sub local2()
18. Dim X As String
19. ' scope of local variable within a function
20. X = "JavaTpoint"
21. Console.WriteLine(" Value of X is {0}", X)
22. End Sub
23. End Module

Output:

Scope of local variable within a function


Value of Local value X is 50
Value of X is JavaTpoint
press any key to exit...

Module Scope
All existing procedures can easily identify a variable that is declared inside
a module sheet is called a module-level variable. The defined module
variable is visible to all procedures within that module only, but it is not
available for other module's procedures. The Dim or private
statement at the top of the first procedure declaration can be declared
the module-level variables. It means that these variables cannot be
declared inside any procedure block. Further, these variables are useful to
share information between the procedures in the same module. And one
more thing about the module-level variable is that these variables can
remains existence as long as the module is executed.

' It is the declaration section of the module

1. Private num As Integer ' A private module-level variable


2. Dim name As String ' Another private module-level variable

Let's create a program that display the module level variable in VB.NET.

Module_scope.vb

1. Imports System
2. Module Module_scope
3. 'module-level variable declaration
4. Dim x As Integer
5. Private y As Integer
6. Private name As String = "JavaTpoint"
7. Sub example()
8. x = 10
9. y = x + 10
10. Console.WriteLine(" Value of Y is {0}", y)
11. End Sub
12. Sub example2()
13. Console.WriteLine(" Value of X is {0}", x)
14. Console.WriteLine(" Value of Y is {0}", y)
15. Console.WriteLine(" Name is {0}", name)
16. End Sub
17. Sub example3()
18. Dim A As Integer ' local variable or local scope
19. A=x+y
20. Console.WriteLine(" Local scope within a function of varia
ble A {0}", A)
21. End Sub
22. Sub Main()
23. Console.WriteLine(" Module scope of variable")
24. example()
25. example2()
26. example3()
27. Console.WriteLine("Press any key to exit...")
28. Console.ReadKey()
29. End Sub
30. End Module

Output:

Module scope of variable


Value of Y is 20
Value of X is 10
Value of Y is 20
Name is JavaTpoint
Local scope within a function of variable A 30
Press any key to exit...

Global (Public) Scope


As the name defines, a global variable is a variable that is used to access
the variables globally in a program. It means these variables can be
accessed by all the procedures or modules available in a program. To
access the variables globally in a program, you need to use the friend or
public keyword with a variable in a module or class at the top of the first
procedure function. Global scope is also known as the Namespace
scope.

Let's create a program that uses the global variable.

Global_scope1.vb

1. Imports System
2. Module Global_scope1
3. 'Global declaration of a variable
4. Public str As String = "Hello, Programmer."
5. Public topic As String
6. Public exp As Integer
7.
8. Sub Main()
9. Console.WriteLine(" You have passed {0}", str)
10. Console.WriteLine(" Enter the topic name")
11. topic = Console.ReadLine
12. Console.WriteLine(" Topic Name :{0}", topic)
13. Console.WriteLine("How many years of experienced in {0
}?", topic)
14. exp = Console.ReadLine
15. Console.WriteLine(" Your Experienced is {0} ", exp)
16. Console.ReadKey()
17. End Sub
18.
19. End Module

Output:

You have passed Hello, Programmer


Enter the topic name
VB.NET
Topic Name :VB.NET
How many years of experienced in VB.NET?
10
Your Experienced is 10

Arithmetic, Relational & Logical operators. I/O in VB: Various controls for I/O in
VB, Message box, Input Box, Print statement.

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

Type Example

Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong
and Char

Floating point Single and Double


types

Decimal types Decimal


Boolean types True or False values, as assigned

Date types Date

VB.Net also allows defining other value types of variable like Enum and
reference types of variables like Class. We will discuss date types and
Classes in subsequent chapters.

Variable Declaration in VB.Net


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

Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

Variable Initialization in VB.Net


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

Example
Try the following example which makes use of various types of variables −
Live Demo

Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double

a = 10
b = 20
c=a+b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
a = 10, b = 20, c = 30
Accepting Values from User
The Console class in the System namespace provides a
function ReadLine for accepting input from the user and store it into a
variable. For example,
Dim message As String
message = Console.ReadLine
The following example demonstrates it −
Live Demo

Module variablesNdataypes
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result (assume the user inputs Hello World) −
Enter message: Hello World
Your Message: Hello World
Lvalues and Rvalues
There are two kinds of expressions −
 lvalue − An expression that is an lvalue may appear as either
the left-hand or right-hand side of an assignment.
 rvalue − An expression that is an rvalue may appear on the
right- but not left-hand side of an assignment.
Variables are lvalues and so may appear on the left-hand side of an
assignment. Numeric literals are rvalues and so may not be assigned and
can not appear on the left-hand side. Following is a valid statement −
Dim g As Integer = 20
But following is not a valid statement and would generate compile-time
error −
20 = g

Different Types of VB.NET Operators

Following are the different types of Operators available in VB.NET:


o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators
o Bit Shift Operators
o Assignment Operators
o Concatenation Operators
o Miscellaneous Operators

Arithmetic Operators
The Arithmetic Operators in VB.NET, used to perform mathematical
operations such as subtraction, addition, multiplication,
division, etc. on the operands in VB.NET. These are as follows:

Arithmetic Operators in VB.NET

Operators Description Example

^ It is an exponentiation Operator that is used to raises Y ^ X (X to


one operand to the power of another operand. the power Y)

+ The addition Operator is used to add numeric data, as X+Y


well as concatenate two string variables.

- It is a subtraction Operator, which is used to subtract X-Y


the second operand from the first operand.

* The multiplication Operator is used to multiply the X*Y


operands

/ It is a division Operator used to divide one operand by X/Y


another operand and returns a floating-point result.

\ It is an integer division Operator, which is similar to X\Y


division Operator, except that it returns an integer
result while dividing one operand to another operand.

Mod It is a modulo (Modulus) Operator, which is used to X Mod Y


divide two operands and returns only a remainder.

Example of Arithmetic Operators in VB.NET:

Arithmetic_Operator.vb
1. Imports System
2. Module Arithmetic_Operator
3. Sub Main()
4. 'Declare a, b And c as integer Data Type()
5. Dim a, b, c As Integer
6. Dim d As Single
7. a = 17
8. b=4
9. ' Use of + Operator
10. c=a+b
11. Console.WriteLine(" Sum of a + b is {0}", c)
12.
13. 'Use of - Operator
14. c=a-b
15. Console.WriteLine(" Subtraction of a - b is {0}", c)
16.
17. 'Use of * Operator
18. c=a*b
19. Console.WriteLine(" Multiplication of a * b is {0}", c)
20.
21. 'Use of / Operator
22. d=a/b
23. Console.WriteLine(" Division of a / b is {0}", d)
24.
25. 'Use of \ Operator
26. c=a\b
27. Console.WriteLine(" Similar to division Operator (return o
nly integer value) of a - b is {0}", c)
28.
29. 'Use of Mod Operator
30. c = a Mod b
31. Console.WriteLine(" Modulus of a Mod b is {0}", c)
32.
33. 'Use of ^ Operator
34. c=a^b
35. Console.WriteLine(" Power of a ^ b is {0}", c)
36. Console.WriteLine("Press any key to exit...")
37. Console.ReadKey()
38. End Sub
39. End Module

Now compile and execute the above program, by pressing the F5 button
or Start button from the Visual Studio; then it shows the following result:

Comparison Operators
As the name suggests, the Comparison Operator is used to compare the
value of two variables or operands for the various condition such as
greater, less than or equal, etc. and returns a Boolean value either true or
false based on the condition.

Operator Description Example

= It checks whether the value of the two (A = B)


operands is equal; If yes, it returns a true
value, otherwise it shows False.

<> It is a Non-Equality Operator that checks (A <> B), check


whether the value of the two operands is not Non-Equality
equal; it returns true; otherwise, it shows
false.

> A greater than symbol or Operator is used to (A > B); if yes,


determine whether the value of the left TRUE,
operand is greater than the value of the right
operand; If the condition is true, it returns Else FALSE
TRUE; otherwise, it shows FALSE value.

< It is a less than symbol which checks whether (A < B); if the
the value of the left operand is less than the condition is true,
value of the right operand; If the condition is returns TRUE else
true, it returns TRUE; otherwise, it shows FALSE
FALSE value.
>= It is greater than equal to which checks two A >= B
conditions whether the first operand is greater
than or equal to the second operand; if yes, it
returns TRUE; otherwise, it shows False.

<= This symbol represents less than equal to A <= B


which determines the first operand is less
than or equal to the second operand, and if
the condition is true, it returns TRUE;
otherwise, it shows FALSE.

Is The Is Operator is used to validate whether result = obj1 Is obj2


the two objects reference the same variable or
object; If the test is true, it returns True;
otherwise, the result is False. In short, it
checks the equality of the objects. An Is
Operator is also used to determine whether
the object refers to a valid object.

IsNot The IsNot Operator is similar to Is Operator, Result = obj1 IsNot


except that the two object references the obj2
different object; if yes, the result is True;
otherwise, the result is False.

Like The Like Operator is used to check the pattern result = string Like
expression of string variable; And if the the pattern, the
pattern matched, the result is True; otherwise, pattern represents
it returns False. the series of
characters used by
Like Operator.

Example of Comparison Operators in VB.NET

Comparison_Operator.vb

1. Imports System
2. Module Comparison_Operator
3. Sub Main()
4. 'declaration of Integer, Object and String Data Type variables
5. Dim x As Integer = 5
6. Dim y As Integer = 10
7. Dim Result, obj, obj2 As Object
8. Dim str, str2 As String
9. str = "Apple12345"
10. str2 = "Apple12345"
11. obj = 10
12. obj2 = 20
13.
14. Console.WriteLine(" Program of Comparison Operator")
15. 'Use of > Operator
16. Console.WriteLine(" Output of x > y is {0}", x > y)
17.
18. 'Use of < Operator
19. Console.WriteLine(" Output of x < y is {0}", x < y)
20.
21. 'Use of = Operator
22. Console.WriteLine(" Output of x = y is {0}", x = y)
23.
24. 'Use of <> Operator
25. Console.WriteLine(" Output of x <> y is {0}", x <> y)
26.
27. 'Use of >= Operator
28. Console.WriteLine(" Output of x >= y is {0}", x >= y)
29.
30. 'Use of <= Operator
31. Console.WriteLine(" Output of x <= y is {0}", x <= y)
32.
33. 'Use of Is Operator
34. Result = obj Is obj2
35. Console.WriteLine(" Output of obj Is obj2 is {0}", Result)
36.
37. 'Use of Is Operator
38. Result = obj IsNot obj2
39. Console.WriteLine(" Output of obj IsNot obj2 is {0}", Resu
lt)
40.
41. 'Use of Like Operator
42. Result = str Like str2
43. Console.WriteLine(" Output of str Like str2 is {0}", Result
)
44.
45. Console.WriteLine(" Press any key to exit...")
46. Console.ReadKey()
47. End Sub
48. End Module

Now compile and execute the above code by pressing the F5 button or
Start button in Visual studio, it returns the following output:

Logical and Bitwise Operators


The logical and bitwise Operators work with Boolean (true or false)
conditions, and if the conditions become true, it returns a Boolean value.
The following are the logical and bitwise Operators used to perform the
various logical operations such as And, Or, Not, etc. on the operands
(variables). Suppose there are two operand A and B, where A is True, and
B is False.

Operato Description Example


r

And The And Operator represents, whether both the (A And B),
operands are true; the result is True. result =
False

Or It is an Or Operator that returns a true value; if anyone (A Or B),


operand is true from both the operands. result = True

Not The Not Operator is used to reverse the logical Not A


condition. For example, if the operand's logic is True, it
reveres the condition and makes it False. Or

Not(A And B)
is True

Xor It is an Exclusive OR Operator that represents, A Xor B is


whether both the expression is true or false, the result True
is True; otherwise, the result is False.

AndAlso It is a logical AND Operator that performs short-circuit A AndAlso B


operation on the variables, and if both the operands = False
are true, the result is True else the result is False.

OrElse It is a logical OR Operator that perform short-circuit A OrElse B =


operation on Boolean data. If anyone of the operand is True
true, the result is True else the result is False.

IsFalse The IsFalse Operator is used to determine whether an


expression is False.

IsTrue The IsTrue Operator is used to determine whether an


expression is True.

Example of Logical and Bitwise Operator:

Logic_Bitwise.vb

1. Imports System
2. Module Logic_Bitwise
3. Sub Main()
4. Dim A As Boolean = True
5. Dim B As Boolean = False
6. Dim c, d As Integer
7. c = 10
8. d = 20
9.
10. 'Use of And Operator
11. If A And B Then
12. Console.WriteLine(" Operands A And B are True")
13. End If
14.
15. 'Use of Or Operator
16. If A Or B Then
17. Console.WriteLine(" Operands A Or B are True")
18. End If
19.
20. 'Use of Xor Operator
21. If A Xor B Then
22. Console.WriteLine(" Operands A Xor B is True")
23. End If
24.
25. 'Use of And Operator
26. If c And d Then
27. Console.WriteLine(" Operands c And d is True")
28. End If
29.
30. 'Use of Or Operator
31. If c Or d Then
32. Console.WriteLine(" Operands c Or d is True")
33. End If
34.
35. 'Use of AndAlso Operator
36. If A AndAlso B Then
37. Console.WriteLine(" Operand A AndAlso B is True")
38. End If
39.
40. 'Use of OrElse Operator
41. If A OrElse B Then
42. Console.WriteLine(" Operand A OrElse B is True")
43. End If
44.
45. 'Use of Not Operator
46. If Not (A And B) Then
47. Console.WriteLine(" Output of Not (A And B) is True")
48. End If
49.
50. Console.WriteLine(" Press any key to exit?")
51. Console.ReadKey()
52. End Sub
53. End Module

Now compile and execute the above code by pressing the F5 button or
Start button in Visual studio, it returns the following output:
Bit Shift Operators
The Bit Shit Operators are used to perform the bit shift operations on
binary values either to the right or to the left.

Bit Shift operations in VB.NET

Operato Description
r

AND The Binary AND Operator are used to copy the common binary bit in
result if the bit exists in both operands.

OR The Binary OR Operator is used to copy a common binary bit in the resu
the bit found in either operand.

XOR The Binary XOR Operator in VB.NET, used to determine whether a b


available to copy in one operand instead of both.

Not The binary NOT Operator is also known as the binary Ones' Complim
Operator, which is used to flip binary bits. This means it converts the
from 0 to 1 or 1 to 0 binary bits.

<< The Binary Left Shift Operator is used to shift the bit to the left side.

>> The Binary Right Shift Operator is used to shift the bit to the right side.

Example of Bit Shift Operator in VB.NET:

BitShift_Operator.vb

1. Imports System
2. Module Bitshift_Operator
3. Sub Main()
4. Dim x, y, z As Integer
5. x = 12
6. y = 25
7. Dim a, b As Double
8. a = 5 ' a = 5(00000101)
9. b = 9 ' b = 9(00001001)
10.
11. ' Use of And Operator
12. z = x And y
13. Console.WriteLine(" BitShift Operator x And y is {0}", z)
14.
15. 'Use of Or Operator
16. z = x Or y
17. Console.WriteLine(" BitShift Operator x Or y is {0}", z)
18.
19. z = x Xor y
20. Console.WriteLine(" BitShift Operator x Xor y is {0}", z)
21.
22. z = Not y
23. Console.WriteLine(" BitShift Operator Not y is {0}", z)
24.
25. 'Use of << Left-Shift Operator
26. ' Output is 00001010
27. Console.WriteLine(" Bitwise Left Shift Operator - a<<1 =
{0}", a << 1)
28.
29. 'Output is 00010010
30. Console.WriteLine(" Bitwise Left Shift Operator - b<<1 =
{0}", b << 1)
31.
32. 'Use of >> Right-Shift Operator
33. 'Output is 00000010
34. Console.WriteLine(" Bitwise Right Shift Operator - a>>1
= {0}", a << 1)
35.
36. 'Output is 00000100
37. Console.WriteLine(" Bitwise Right Shift Operator - b>>1
= {0}", a << 1)
38.
39. Console.WriteLine(" Press any key to exit...")
40. Console.ReadKey()
41. End Sub
42. End Module

Now compile and execute the above code by pressing the F5 button or
Start button in Visual studio, it returns the following output:

Assignment Operators
The Assignment Operators are used to assign the value to variables in
VB.NET.

Assignment Operators in VB.NET

Operato Description Example


r

= It is a simple assignment Operator used to assign a X = 5, X assign a v


right-side operand or value to a left side operand. 5
X = P + Q, (P +
variables or v
assign to X.

+= An Add AND assignment Operator is used to add X += 5, which me


the value of the right operand to the left operand. X= X+5 ( 5 will add
And the result is assigned to the left operand. assign to X and t
result saved to Le
operand)

-= It is a Subtract AND assignment Operator, which X -= P, which is sam


subtracts the right operand or value from the left X=X-P
operand. And then, the result will be assigned to
the left operand.

*= It is a Multiply AND assignment Operator, which X *= P, which is sa


multiplies the right operand or value with the left as X = X - P
operand. And then, the result will be assigned to
the left operand.

/= It is a Divide AND assignment Operator, which X /= P, which is sam


divides the left operand or value with the right X=X-P
operand. And then, the result will be assigned to
the left operand (in floating-point).

\= It is a Divide AND assignment Operator, which X \= P, which is sam


divides the left operand or value with the right X=X-P
operand. And then, the result will be assigned to
the left operand (in integer-point division).

^= It is an expression AND assignment Operator, which X ^= P, which is sa


raises the left operand or value to the right as X = X ^ P
operand's power. And then, the result will be
assigned to the left operand.

&= It is a concatenate string assignment Operator used Str &= name, whic
to bind the right-hand string or variable with the same as Str = St
left-hand string or variable. And then, the result will name
be assigned to the left operand.

Example of Assignment Operator in VB.NET:

Assign_Operator.vb

1. Imports System
2. Module Assign_Operator
3. Sub Main()
4. 'Declare variable and b As Integer
5. Dim A As Integer = 5
6. Dim B As Integer
7. Dim Str, name As String
8. name = "come"
9. Str = "Wel"
10.
11. 'Use of = Operator
12. B=A
13. Console.WriteLine(" Assign value A to B is {0}", B)
14.
15. 'Use of += Operator
16. B += A
17. Console.WriteLine(" Output of B += A is {0}", B)
18.
19. 'Use of -= Operator
20. B -= A
21. Console.WriteLine(" Output of B -= A is {0}", B)
22.
23. 'Use of *= Operator
24. B *= A
25. Console.WriteLine(" Output of B *= A is {0}", B)
26.
27. 'Use of /= Operator
28. B /= A
29. Console.WriteLine(" Output of B /= A is {0}", B)
30.
31. 'Use of = Operator
32. B \= A
33. Console.WriteLine(" Output of B \= A is {0}", B)
34.
35. 'Use of ^= Operator
36. B ^= A
37. Console.WriteLine(" Output of B ^= A is {0}", B)
38.
39. 'Use of &= Operator
40. Str &= name
41. Console.WriteLine(" Output of Str &= name is {0}", Str)
42.
43. Console.WriteLine(" Press any key to exit...")
44. Console.ReadKey()
45. End Sub
46. End Module

Now compile and execute the above code by pressing the F5 button or
Start button in Visual studio, it returns the following output:
Concatenation Operators
In VB.NET, there are two concatenation Operators to bind the operands:

Operato Description Example


r

& It is an ampersand symbol that is used to bind two or more Result


operand together. Furthermore, a nonstring operand can also Wel
be concatenated with a string variable ( but in that case, Option come,
Strict is on). Result
Welcome

+ It is also used to add or concatenate two number or string. Result


Wel
come,
Result
Welcome

Example of Concatenation Operators in VB.NET.

MyProgram.vb

1. Imports System
2. Module MyProgram
3. Sub Main()
4. Dim str As String = "Wel"
5. Dim str2 As String = "come"
6. Dim str3 As String = " "
7. Dim str4 As String = "to JavatPoint"
8. Dim result As String
9. Dim result2 As String
10. result = str & str2
11. Console.WriteLine(" Result = str & str2 gives = {0}", resu
lt)
12. result2 = str + str2 + str3 + str4
13. Console.WriteLine(" Result = str + str2 + str3 +str4 gives
= {0}", result2.ToString)
14. Console.ReadLine()
15. End Sub
16. End Module

Now compile and execute the above code by pressing the F5 button or
Start button in Visual studio, it returns the following output:

Miscellaneous Operators
There are some important Operator in VB.NET

Operator Description Example

Await An Await Operator is used in an Dim output as out = A


operand to suspend the execution of AsyncMethodThatReturnsResult()
an asynchronous method or lambda Await AsyncMethod()
expression until the awaited task
completes.

AddressOf The AddressOf Operator is used to AddHandler Button2.Click, Addres


provide a reference to the address of Button2_Click
a procedure.

GetType A GetType Operator is used to MsgBox(GetType(String).ToString(


retrieve the type of the specified
object. In addition, the retrieved
object type provides various
information such as methods,
properties, and events.

Function It defines the lambda expression, Dim mul2 = Function(num


Expression which declares the parameter and Integer) num *
code. A Lambda expression is a Console.WriteLine(mul2(4))
function that is used to calculate and
return value without defining the
name.

If The If Operator using short circuit Dim a =


evaluation to conditionally return a Console.WriteLine(If (a >=
single object value from two defined "Positive", "Negative"))
object values. The If Operator can be
used with two or three defined
arguments.

Example of Miscellaneous Operators in VB.NET.

Misc_Operator.vb

1. Imports System
2. Module Misc_Operator
3. Sub Main()
4. ' Initialize a variable
5. Dim a As Integer = 50
6. ' GetType of the Defined Type
7. Console.WriteLine(GetType(Double).ToString())
8. Console.WriteLine(GetType(Integer).ToString())
9. Console.WriteLine(GetType(String).ToString())
10. Console.WriteLine(GetType(Single).ToString())
11. Console.WriteLine(GetType(Decimal).ToString())
12.
13. 'Use of Function()
14. Dim multiplywith10 = Function(sum As Integer) sum * 10
15. Console.WriteLine(multiplywith10(10))
16. Console.WriteLine(If(a >= 0, "Negative", "Positive"))
17.
18. Console.WriteLine(" Press any key to exit...")
19. Console.ReadLine()
20.
21. End Sub
22. End Module

Now compile and execute the above code by pressing the F5 button or
Start button in Visual studio, it returns the following output:
Operator Precedence in VB.NET
Operator precedence is used to determine the order in which different
Operators in a complex expression are evaluated. There are distinct levels
of precedence, and an Operator may belong to one of the levels. The
Operators at a higher level of precedence are evaluated first. Operators of
similar precedents are evaluated at either the left-to-right or the right-to-
left level.

The Following table shows the operations, Operators and their precedence
-

Operations Operators Precede

Await Highest

Exponential ^

Unary identity and negation +, -

Multiplication and floating- *, /


point division

Integer division \

Modulus arithmetic Mod

Addition and Subtraction +, -

Arithmetic bit shift <<, >>

All comparison Operators =, <>, <, <=, >, >=, Is, IsNot,
Like, TypeOf …is

Negation Not

Conjunction And, AndAlso


Inclusive disjunction Or, Else

Exclusive disjunction Xor Lowest

Example of Operator Precedence in VB.NET.

Operator_Precedence.vb

1. Imports System
2. Module Operator_Precedence
3. Sub Main()
4. 'Declare and Initialize p, q, r, s variables
5. Dim p As Integer = 30
6. Dim q As Integer = 15
7. Dim r As Integer = 10
8. Dim s As Integer = 5
9. Dim result As Integer
10.
11. Console.WriteLine("Check Operator Precedence in VB.NET
")
12. 'Check Operator Precedence
13. result = (p + q) * r / s ' 45 * 10 / 5
14. Console.WriteLine("Output of (p + q) * r / s is : {0}", resul
t)
15.
16. result = (p + q) * (r / s) ' (45) * (10/5)
17. Console.WriteLine("Output of (p + q) * (r / s) is : {0}", re
sult)
18.
19. result = ((p + q) * r) / s ' (45 * 10 ) / 5
20. Console.WriteLine("Output of ((p + q) * r) / s is : {0}", re
sult)
21.
22. result = p + (q * r) / s ' 30 + (150/5)
23. Console.WriteLine("Output of p + (q * r) / s is : {0}", resu
lt)
24.
25. result = ((p + q * r) / s) ' ((30 + 150) /5)
26. Console.WriteLine("Output of ((p + q * r) / s) is : {0}", re
sult)
27.
28. Console.WriteLine(" Press any key to exit...")
29. Console.ReadKey()
30. End Sub
31. End Module

Now compile and execute the above code by pressing the F5 button or
Start button in Visual studio, it returns the following output:

VB.NET Control Statements


In VB.NET, the control statements are the statements that controls the execution of the p
on the basis of the specified condition. It is useful for determining whether a condition is true o
the condition is true, a single or block of statement is executed. In the control statement,
use if- Then, if Then Else, if Then ElseIf and the Select case statement.

We can define more than one condition to be evaluated by the program with statements
defined condition is true, the statement or block executes according to the condition, and
condition is false, another statement is executed.

The following figure shows a common format of the decision control statements to valida
execute a statement:
The above diagram shows that if the defined condition is true, statement_1 will be executed
the condition is false, statement_2 will be executed.

Backward Skip 10sPlay VideoForward Skip 10s

VB.NET provides the following conditional or decision-making statements.

o If-Then Statement
o If-Then Else Statement
o If-Then ElseIf Statement
o Select Case Statement
o Nested Select Case Statements

If-Then Statement
The If-Then Statement is a control statement that defines one or more conditions, and
particular condition is satisfied, it executes a piece of information or statements.
Syntax:

1. If condition Then
2. [Statement or block of Statement]
3. End If

In If-Then Statement, the condition can be a Boolean, logical, or relational condition, a


statement can be single or group of statements that will be executed when the condition is true

Example 1: Write a simple program to print a statement in VB.NET.

Module1.vb

1. Module Module1
2. ' Declaration of variable str
3. Dim str As String = "JavaTpoint"
4. Sub Main()
5. ' if str equal to "JavaTpoint", below Statement will be executed.
6. If str = "JavaTpoint" Then
7. Console.WriteLine("Welcome to the JavaTpoint")
8. End If
9. Console.WritLine("press any key to exit?")
10. Console.ReadKey()
11. End Sub
12. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:

As we can see in the above example, if the value of str is equal to JavaTpoint, the condition
and it prints the Statement.

Example 2: Write a program to print a number is greater than another number in VB.NET.

if_statment2.vb
1. Module if_statement2
2. Sub Main()
3. ?Definition of variables
4. Dim no1, no2 As Integer
5. Console.WriteLine("Enter any two number:")
6. no1 = Console.ReadLine() ?read no1 from user
7. no2 = Console.ReadLine() ?read no2 from user
8. If no1 > no2 Then
9. Console.WriteLine("First number is greater than second number")
10. End If
11. If no1 < no2 Then
12. Console.WriteLine("Second number is greater than First number")
13. End If
14. Console.WriteLine("press any key to exit...")
15. Console.ReadKey()
16. End Sub
17. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:

In the above program, we enter two numbers to find the greater number using the relational op
And if the first number is greater than the other, the first statement is executed; otherwi
second statement will be executed.

If-Then-Else Statement
The If-Then Statement can execute single or multiple statements when the condition is tr
when the expression evaluates to false, it does nothing. So, here comes the If-Then-Else Sta
The IF-Then-Else Statement is telling what If condition to do when if the statement is false, it ex
the Else statement. Following is the If-Then-Else statement syntax in VB.NET as follows:

Syntax:
1. If (Boolean_expression) Then
2. 'This statement will execute if the Boolean condition is true
3. Else
4. 'Optional statement will execute if the Boolean condition is false
5. End If

Flow chart

The above diagram represents that if the Boolean expression (condition) is true, the if statem
execute, and if the Boolean expression is false, Else code or statement will be executed. Aft
the control transfer to the next statement, which is immediately after the If-Then-Else
statement.

Example 1: Write a program to check whether the number is even or odd.

If_Else_statment.vb

1. Module If_Else_statement
2. Sub Main()
3. Dim num As Integer
4. Console.WriteLine("Enter the Number")
5. num = Console.ReadLine() 'read data from console
6.
7. If (num Mod 2 = 0) Then ' if condition is true, print the if statement
8. Console.WriteLine("It is an even number")
9.
10. Else 'otherwise, Else statement is executed.
11. Console.WriteLine("It is an odd number")
12. End If
13.
14. Console.WriteLine("press any key to exit...")
15. Console.ReadKey()
16. End Sub
17. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:

Example 2: Write a program to print the larger and smaller of the two numbers.

if_else_statment2.vb

1. Module if_else_statement2
2. Sub Main()
3. Dim a As Integer
4. Dim b As Integer
5. Console.WriteLine("Enter the first number : ")
6. a = Console.ReadLine()
7.
8. Console.WriteLine("Enter the second number : ")
9. b = Console.ReadLine()
10.
11. If a > b Then
12. Console.WriteLine(" larger number = {0} and smaller number = {1} ", a, b
13. Else
14. Console.WriteLine(" larger number = {0} and smaller number = {1} ", b, a
15. End If
16.
17. Console.WriteLine("press any key to exit...")
18. Console.ReadKey()
19. End Sub
20. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:

VB.NET If-Then-ElseIf statement


The If-Then-ElseIf Statement provides a choice to execute only one condition or statemen
multiple statements. Execution starts from the top to bottom, and it checked for each If conditi
if the condition is met, the block of If the statement is executed. And if none of the conditi
true, the last block is executed. Following is the syntax of If-Then-ElseIf Statement in VB.
follows:

Syntax

1. If(condition 1)Then
2. ' Executes when condition 1 is true
3. ElseIf( condition 2)Then
4. ' Executes when condition 2 is true
5. ElseIf( boolean_expression 3)Then
6. ' Executes when the condition 3 is true
7. Else
8. ' executes the default statement when none of the above conditions is true.
9. End If
Flowchart

The following diagram represents the functioning of the If-Else-If Statement in the
programming language.

If this condition is true in the flowchart of the if-else-if statement, the statement is executed wit
if block. If the condition is not true, it passes control to the next ElseIf condition to check whet
condition is matched. And if none of the conditions are matched, the else block is executed.

Example 1: Write a program to show the uses of If... ElseIf statements.

if_elseIf.vb

1. Module if_elseIf
2. Sub Main()
3. Dim var1 As Integer
4.
5. Console.WriteLine(" Input the value of var1: ")
6. var1 = Console.ReadLine()
7. If var1 = 20 Then
8. 'if condition is true then print the following statement'
9. Console.WriteLine(" Entered value is equal to 20")
10. ElseIf var1 < 50 Then
11. Console.WriteLine(" Entered value is less than 50")
12.
13. ElseIf var1 >= 100 Then
14. Console.WriteLine(" Entered value is greater than 100")
15. Else
16. 'if none of the above condition is satisfied, print the following statement
17. Console.WriteLine(" Value is not matched with above condition")
18. End If
19. Console.WriteLine(" You have entered : {0}", var1)
20. Console.WriteLine(" press any key to exit...")
21. Console.ReadKey()
22. End Sub
23. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:

Example 2: Write a program to use the If-Then-ElseIf Statement for calculating the division o
by the student. Also, take the marks obtained by the student in 5 different subjects fro
keyboard.

if_elseIf2.vb

1. Module If_elseIf2
2. Sub Main() ' execution start from Main() method
3. Dim m1, m2, m3, m4, m5, per As Integer
4. Console.WriteLine("Enter marks in five subjects ")
5. ' Read the marks of five subject
6. m1 = Console.ReadLine()
7. m2 = Console.ReadLine()
8. m3 = Console.ReadLine()
9. m4 = Console.ReadLine()
10. m5 = Console.ReadLine()
11. per = (m1 + m2 + m3 + m4 + m5) / 5
12. If (per >= 70) Then
13. 'if condition is true, print the first division
14. Console.WriteLine(" First division")
15. ElseIf (per >= 60) Then
16. 'if ElseIf condition is true, print the second division
17. Console.WriteLine(" Second division")
18. ElseIf (per >= 50) Then
19. 'if ElseIf condition is true, print the third division
20. Console.WriteLine(" Third division")
21. ElseIf (per >= 40) Then
22. 'if ElseIf condition is true, print only pass with grace
23. Console.WriteLine(" Only Pass with Grace")
24. Else
25. 'if none of the condition is true, print the Failed
26. Console.WriteLine(" Failed")
27. End If
28. Console.WriteLine("press any key to exit...")
29. Console.ReadKey()
30. End Sub
31.
32. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:
Select Case Statement
In VB.NET, the Select Case statement is a collection of multiple case statements, which
executing a single case statement from the list of statements. A selected case statement
variable to test for equality against multiple cases or statements in a program. If the var
matched with any test cases, that statement will be executed. And if the condition is not m
with any cases, it executes the default statement.

Using the select case statement in VB.NET programming, you can replace the uses of multiple
Else If statement from the program for better readability and easy to use.

Syntax

Following is the syntax of the Select Case statement in VB.NET, as follows:

1. Select Case [variable or expression]


2. Case value1 'defines the item or value that you want to match.
3. // Define a statement to execute
4.
5. Case value2 'defines the item or value that you want to match.
6. // Define a statement to execute
7.
8. Case Else
9. // Define the default statement if none of the conditions is true.
10. End Select

Furthermore, you can also set more than one condition in a single case statement, such as:

1. Select Case Variable / expression


2. Case value1
3. Statement1
4.
5. Case value2, value3
6. Statement2
7.
8. Case Else
9. // define the default statement if none of the condition is true
10. End Select

Flowchart of Select Case Statement

The following flowchart represents the functioning of the Select case statement in the
programming language.

In Flowchart, the Select Case statement represents the evaluating of the process start from
bottom. If the expression or value is matched with the first select case, statement -1 is execut
the control transfer to the next case for checking whether the expression is matching or not. Si
it checks all Select case statements for evaluating. If none of the cases are matched, the Els
statement will be executed, and finally, the Select Case Statement will come to an end.

Example 1 : Write a program to display th


name using the select case statement in VB.NET.

Select_case.vb

1. Imports System
2. Module Select_case
3. Sub Main()
4. 'define a local variable.
5. Dim Days As String
6. Days = "Thurs"
7. Select Case Days
8. Case "Mon"
9. Console.WriteLine(" Today is Monday")
10. Case "Tue"
11. Console.WriteLine(" Today is Tuesday")
12. Case "Wed"
13. Console.WriteLine("Today is Wednesday")
14. Case "Thurs"
15. Console.WriteLine("Today is Thursday")
16. Case "Fri"
17. Console.WriteLine("Today is Friday")
18. Case "Sat"
19. Console.WriteLine("Today is Saturday")
20. Case "Sun"
21. Console.WriteLine("Today is Sunday")
22. Case Else
23. Console.WriteLine(" You have typed Something wrong")
24.
25. End Select
26. Console.WriteLine("You have selected : {0}", Days)
27. Console.WriteLine("Press any key to exit...")
28. Console.ReadLine()
29. End Sub
30. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:
In the select case statement, the value of Days "Thurs" will compare all the available select
values in a program. If a value matched with any condition, it prints the particular statement
the value is not matched with any select case statement, it prints the default message.

Example 2: Write a program to perform an arithmetic operation using the Select case statem
VB.NET.

Operation.vb

Operation.vb

1. Imports System
2. Module Operation
3. Sub main()
4. 'declaration of the variables
5. Dim num1, num2, sum As Integer
6. Dim def As Char
7. 'initialization of num1 and num2 variable
8. num1 = 2
9. num2 = 6
10. Console.WriteLine(" Want to perform any operation?")
11. Console.WriteLine(" A for Addition")
12. Console.WriteLine(" S for Subtraction")
13. Console.WriteLine(" M for Multiplication")
14. Console.WriteLine(" D for Division")
15. Console.WriteLine(" Please enter any input")
16. def = Console.ReadLine()
17. Select Case def
18. Case "A"
19. 'perform Addition
20. sum = num1 + num2
21. Console.WriteLine(" Addition of two number is :{0}", sum)
22. Case "S"
23. 'perform Subtraction
24. sum = num2 - num1
25. Console.WriteLine(" Subtraction of two number is :{0}", sum)
26. Case "M"
27. 'perform Multiplication
28. sum = num1 * num2
29. Console.WriteLine(" Multiplication of two number is :{0}", sum)
30. Case "D"
31. 'Peform Division
32. sum = num2 / num1
33. Console.WriteLine(" Division of two number is :{0}", sum)
34. Case Else
35. 'If none of the operation matched, call default statement
36. Console.WriteLine(" Please enter only define operation With Capital letter
37. End Select
38. Console.WriteLine("Press any key to exit...")
39. Console.ReadKey()
40. End Sub
41. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:

In the above example, we defined Select with multiple case statements, and if th
defined input is matched with any defined case statement, it executes that statement. And
condition is not matched with any case, it executes a default statement in VB.NET.

Here, we provide 'M' as input, which checks all case statements, and if any case is matched w
executes the statement within the respective Case statement.

VB.NET Nested Select Case statements


When a Select Case statement is written inside the body of another Select Case statem
called a nested Select Case statement.

Syntax:

1. Select Case "num"


2. ' code to be executed if num = 1
3. Case 1
4. ' nested Select case
5. Select Case n
6.
7. ' code to be executed if n = 5
8. Case 5
9. Statement 1
10.
11. ' code to be executed if n = 10
12. Case 10
13. Statement 2
14.
15. ' code to be executed if n = 15
16. Case 15
17. Statement 3
18.
19. ' code to be executed if n doesn't match with any cases.
20. Case Else
21. Statement
22.
23. ' code to be executed if num = 2
24. Case 2
25. Statement 2
26.
27. ' code to be executed if num = 3
28. Case 3
29. Statement 3
30.
31. ' code to be executed if num doesn't match with any cases.
32. Case Else
33. Statement

Example 1: Write a program to use a nested select case statement in VB.NET.

Module1.vb

1. Module Module1
2.
3. Sub Main()
4.
5. Dim x As Integer = 10, y As Integer = 5
6. Select Case x
7.
8. Case 10
9. Console.WriteLine("X Value: 10")
10.
11.
12. Select Case y
13. Case 5
14. Console.WriteLine("Nested Switch Value: 5")
15.
16.
17. Select Case y - 2
18. Case 3
19. Console.WriteLine("Another Nested Switch Value: 3")
20.
21. End Select
22. End Select
23.
24. Case 15
25. Console.WriteLine("X Value: 15")
26.
27. Case 20
28. Console.WriteLine("X Value: 20")
29.
30. Case Else
31. Console.WriteLine("Not Known")
32.
33. End Select
34. Console.WriteLine("Press Enter Key to Exit..")
35. Console.ReadLine()
36. End Sub
37. End Module

Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:

Example 2: Write a program to use the nested select case statement in VB.NET.

nested_selectcase.vb

1. Imports System
2. Module nested_selectcase
3. Sub Main()
4. Dim num As Integer
5. Dim str As String
6. str = "F"
7.
8. Console.WriteLine(" Enter only First three number like 1, 2, 3")
9. num = Console.ReadLine() 'take input from the user
10. Select Case num
11. Case 1
12. Console.WriteLine(" You are in block 1")
13. Console.WriteLine("Only First two letter such as A and B")
14.
15. str = Console.ReadLine()
16. Select Case str
17. Case "A", "a"
18. Console.WriteLine(" This is a VB.NET Tutorial")
19. Case "B", "b"
20. Console.WriteLine(" Welcome to the JavaTpoint")
21. Case Else
22. Console.WriteLine(" Something is wrong")
23. End Select
24.
25. Case 2
26. Console.WriteLine(" You are in block 2")
27. Console.WriteLine("Only First two letter such as C and D")
28. str = Console.ReadLine()
29. Select Case str
30. Case "C", "c"
31. Console.WriteLine(" Welcome to the World!")
32. Case "D", "d"
33. Console.WriteLine(" Want to go in Heaven")
34. Case Else
35. Console.WriteLine(" Something is wrong")
36. End Select
37.
38. Case 3
39. Console.WriteLine(" You are in block 3")
40. Console.WriteLine("Only First two letter such as E and F")
41. str = Console.ReadLine()
42. Select Case str
43. Case "E", "e"
44. Console.WriteLine(" VB.NET is a programming language to develop w
ndow, and console-based application. ")
45. Case "F", "f"
46. Console.WriteLine(" You have to basic knowledge of c and c++")
47. Case Else
48. Console.WriteLine(" Something is wrong")
49. End Select
50. Case Else
51. Console.WriteLine(" Something is wrong")
52. End Select
53. Console.ReadLine()
54. End Sub
55. End Module
Now compile and execute the above program by clicking on the Start or F5 button, it sho
following output:

In the above example, we have only defined the first three numbers 1-3 and if the number mat
any case statement, the select statement is executed. Here, we have entered 2 that is match
case 2 and it executes a block as shown above. And this block executes the statement "Only t
two letters such as C and D". Therefore, we enter a letter D, letter D is matched with the nested
case statement, and if a match is found, it executes the select case statement as shown above

12.1 MsgBox ( ) Function

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

yourMsg=MsgBox(Prompt, Style Value, Title)

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

Table 12.1: Style Values


Style
Named Constant Buttons Displayed
Value
0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
Abort, Retry and Ignore
2 vbAbortRetryIgnore
buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons
We can use named constants in place of integers for the second argument to make the pr
more readable. In fact, Visual Basic 2012 will automatically shows up a list of named constants
you can select one of them.

For example:

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

and

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

are the same.

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

Table 12.2 : Return Values and Command


Buttons
Named Button
Value
Constant Clicked
1 vbOk Ok button
2 vbCancel Cancel button
3 vbAbort Abort button
4 vbRetry Retry button
5 vbIgnore Ignore button
6 vbYes Yes button
7 vbNo No button
Example 12.1

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


Button1.Click

Dim testmsg As Integer

testmsg = MsgBox("Click to test", 1, "Test message")

If testmsg = 1 Then

MessageBox.Show("You have clicked the OK button")

Else
MessageBox.Show("You have clicked the Cancel button")

End If

End Sub

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

Table 12.3 Types of Icons


Valu Named Ico
e Constant n

16 vbCritical

3 vbQuestion

48 vbExclamation

64 vbInformation
Example 12.2

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


Button1.Click

Dim testMsg As Integer

testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")

If testMsg = 6 Then

MessageBox.Show("You have clicked the yes button")

ElseIf testMsg = 7 Then

MessageBox.Show("You have clicked the NO button")

Else

MessageBox.Show("You have clicked the Cancel button")

End If

End Sub
The first argument, Prompt, will display the message

Figure 12.1 The MessageBox

12.2 The InputBox( ) Function

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

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

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

Prompt - the message displayed normally as a question asked.

Title - The title of the Input Box.

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

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

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

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

The parameters remain the same.

Example 12.3

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


Button1.Click

Dim userMsg As String

userMsg = Microsoft.VisualBasic.InputBox("What is your message?", "Message Entry


"Enter your messge here", 500, 700)

If userMsg <> "" Then

MessageBox.Show(userMsg)

Else
MessageBox.Show("No Message")

End If

End Sub

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

Section C: Unit III


Programming with VB: Decisions and conditions: If statement, If-then-else,
Select-case. Looping statements: Do-loops, For-next, While-wend, Exit
statement. Nested control structures.
OPERATORS IN VISUAL BASIC
An operator is a special symbol which indicates a certain process is carried out.
Operators in programming languages are taken from mathematics.
Programmers work with data. The operators are used to process data.
ARITHMETICAL OPERATORS Arithmetic operators are used to perform many of
the familiar arithmetic operations that involve the calculation of numeric values
represented by literals, variables, other expressions, function and property
calls, and constants. Also classified with arithmetic operators are the bitshift
operators, which act at the level of the individual bits of the operands and shift
their bit patterns to the left or right

Operators Description Example Result + Add 5+5 10 - Subtract 10-5 5 / Divide


25/5 5 \ Integer Division 20\3 6 * Multiply 5*4 20 ^ Exponent (power of) 3^3 27
Mod Remainder of division 20 Mod 6 2 & String concatenation "George"&"
"&"Bush" "George Bush" COMPARISON/CONDITIONAL/RELATIONAL
OPERATORS Comparison operators compare two expressions and return a
Boolean value that represents the relationship of their values. There are
operators for comparing numeric values, operators for comparing strings, and
operators for comparing objects. Visual Basic compares numeric values using
six numeric comparison operators. Each operator takes as operands two
expressions that evaluate to numeric values. The following table lists the
operators and shows examples of each. Operators Description Example Result >
Greater than 10>8 True < Less than 10= Greater than or equal to 20>=10 True
<= Less than or equal to 10<=20 True <> Not Equal to 5<>4 True = Equal to 5=7
False *Note: You can also compare strings with the above operators. However,
there are certain rules to follows: Upper case letters are less than lowercase
letters, "A"<"B"<"C"<"D".......<"Z" and number are less than letters. LOGICAL
OPERATORS In addition to conditional operators, there are a few logical
operators which offer added power to the VB programs. Logical operators
compare Boolean expressions and return a Boolean result. The And, Or,
AndAlso, OrElse, and Xor operators are binary because they take two operands,
while the Notoperator is unary because it takes a single operand. Some of
these operators can also perform bitwise logical operations on integral values

VB.NET Control Statements


In VB.NET, the control statements are the statements that controls the
execution of the program on the basis of the specified condition. It is
useful for determining whether a condition is true or not. If the condition is
true, a single or block of statement is executed. In the control statement,
we will use if- Then, if Then Else, if Then ElseIf and the Select
case statement.

We can define more than one condition to be evaluated by the program


with statements. If the defined condition is true, the statement or block
executes according to the condition, and if the condition is false, another
statement is executed.

The following figure shows a common format of the decision control


statements to validate and execute a statement:
The above diagram shows that if the defined condition is true,
statement_1 will be executed, and if the condition is false, statement_2
will be executed.

PauseNext
Unmute

Current Time 0:01

Duration 18:10
Loaded: 0.37%
Â
Fullscreen

VB.NET provides the following conditional or decision-making statements.

o If-Then Statement
o If-Then Else Statement
o If-Then ElseIf Statement
o Select Case Statement
o Nested Select Case Statements

If-Then Statement
The If-Then Statement is a control statement that defines one or more
conditions, and if the particular condition is satisfied, it executes a piece of
information or statements.

Syntax:

1. If condition Then
2. [Statement or block of Statement]
3. End If

In If-Then Statement, the condition can be a Boolean, logical, or


relational condition, and the statement can be single or group of
statements that will be executed when the condition is true.

Example 1: Write a simple program to print a statement in VB.NET.

Module1.vb

1. Module Module1
2. ' Declaration of variable str
3. Dim str As String = "JavaTpoint"
4. Sub Main()
5. ' if str equal to "JavaTpoint", below Statement will be executed.

6. If str = "JavaTpoint" Then


7. Console.WriteLine("Welcome to the JavaTpoint")
8. End If
9. Console.WritLine("press any key to exit?")
10. Console.ReadKey()
11. End Sub
12. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:
As we can see in the above example, if the value of str is equal
to JavaTpoint, the condition is true, and it prints the Statement.

Example 2: Write a program to print a number is greater than another


number in VB.NET.

if_statment2.vb

1. Module if_statement2
2. Sub Main()
3. ?Definition of variables
4. Dim no1, no2 As Integer
5. Console.WriteLine("Enter any two number:")
6. no1 = Console.ReadLine() ?read no1 from user
7. no2 = Console.ReadLine() ?read no2 from user
8. If no1 > no2 Then
9. Console.WriteLine("First number is greater than second num
ber")
10. End If
11. If no1 < no2 Then
12. Console.WriteLine("Second number is greater than Firs
t number")
13. End If
14. Console.WriteLine("press any key to exit...")
15. Console.ReadKey()
16. End Sub
17. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:
In the above program, we enter two numbers to find the greater number
using the relational operator. And if the first number is greater than the
other, the first statement is executed; otherwise, the second statement
will be executed.

If-Then-Else Statement
The If-Then Statement can execute single or multiple statements when
the condition is true, but when the expression evaluates to false, it does
nothing. So, here comes the If-Then-Else Statement. The IF-Then-Else
Statement is telling what If condition to do when if the statement is false,
it executes the Else statement. Following is the If-Then-Else statement
syntax in VB.NET as follows:

Syntax:

1. If (Boolean_expression) Then
2. 'This statement will execute if the Boolean condition is true
3. Else
4. 'Optional statement will execute if the Boolean condition is false
5. End If

Flow chart
The above diagram represents that if the Boolean expression (condition)
is true, the if statement will execute, and if the Boolean expression is
false, Else code or statement will be executed. After that, the control
transfer to the next statement, which is immediately after the If-Then-Else
control statement.

Example 1: Write a program to check whether the number is even or odd.

If_Else_statment.vb

1. Module If_Else_statement
2. Sub Main()
3. Dim num As Integer
4. Console.WriteLine("Enter the Number")
5. num = Console.ReadLine() 'read data from console
6.
7. If (num Mod 2 = 0) Then ' if condition is true, print the if state
ment
8. Console.WriteLine("It is an even number")
9.
10. Else 'otherwise, Else statement is executed.
11. Console.WriteLine("It is an odd number")
12. End If
13.
14. Console.WriteLine("press any key to exit...")
15. Console.ReadKey()
16. End Sub
17. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:

Example 2: Write a program to print the larger and smaller of the two
numbers.

if_else_statment2.vb

1. Module if_else_statement2
2. Sub Main()
3. Dim a As Integer
4. Dim b As Integer
5. Console.WriteLine("Enter the first number : ")
6. a = Console.ReadLine()
7.
8. Console.WriteLine("Enter the second number : ")
9. b = Console.ReadLine()
10.
11. If a > b Then
12. Console.WriteLine(" larger number = {0} and smaller
number = {1} ", a, b)
13. Else
14. Console.WriteLine(" larger number = {0} and smaller
number = {1} ", b, a)
15. End If
16.
17. Console.WriteLine("press any key to exit...")
18. Console.ReadKey()
19. End Sub
20. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:

VB.NET If-Then-ElseIf statement


The If-Then-ElseIf Statement provides a choice to execute only one
condition or statement from multiple statements. Execution starts from
the top to bottom, and it checked for each If condition. And if the condition
is met, the block of If the statement is executed. And if none of the
conditions are true, the last block is executed. Following is the syntax of
If-Then-ElseIf Statement in VB.NET as follows:

Syntax

1. If(condition 1)Then
2. ' Executes when condition 1 is true
3. ElseIf( condition 2)Then
4. ' Executes when condition 2 is true
5. ElseIf( boolean_expression 3)Then
6. ' Executes when the condition 3 is true
7. Else
8. ' executes the default statement when none of the above conditio
ns is true.
9. End If
Flowchart

The following diagram represents the functioning of the If-Else-If


Statement in the VB.NET programming language.

If this condition is true in the flowchart of the if-else-if statement, the


statement is executed within the if block. If the condition is not true, it
passes control to the next ElseIf condition to check whether the condition
is matched. And if none of the conditions are matched, the else block is
executed.

Example 1: Write a program to show the uses of If... ElseIf statements.

if_elseIf.vb

1. Module if_elseIf
2. Sub Main()
3. Dim var1 As Integer
4.
5. Console.WriteLine(" Input the value of var1: ")
6. var1 = Console.ReadLine()
7. If var1 = 20 Then
8. 'if condition is true then print the following statement'
9. Console.WriteLine(" Entered value is equal to 20")
10. ElseIf var1 < 50 Then
11. Console.WriteLine(" Entered value is less than 50")
12.
13. ElseIf var1 >= 100 Then
14. Console.WriteLine(" Entered value is greater than 100"
)
15. Else
16. 'if none of the above condition is satisfied, print the foll
owing statement
17. Console.WriteLine(" Value is not matched with above c
ondition")
18. End If
19. Console.WriteLine(" You have entered : {0}", var1)
20. Console.WriteLine(" press any key to exit...")
21. Console.ReadKey()
22. End Sub
23. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:

Example 2: Write a program to use the If-Then-ElseIf Statement for


calculating the division obtained by the student. Also, take the marks
obtained by the student in 5 different subjects from the keyboard.

if_elseIf2.vb

1. Module If_elseIf2
2. Sub Main() ' execution start from Main() method
3. Dim m1, m2, m3, m4, m5, per As Integer
4. Console.WriteLine("Enter marks in five subjects ")
5. ' Read the marks of five subject
6. m1 = Console.ReadLine()
7. m2 = Console.ReadLine()
8. m3 = Console.ReadLine()
9. m4 = Console.ReadLine()
10. m5 = Console.ReadLine()
11. per = (m1 + m2 + m3 + m4 + m5) / 5
12. If (per >= 70) Then
13. 'if condition is true, print the first division
14. Console.WriteLine(" First division")
15. ElseIf (per >= 60) Then
16. 'if ElseIf condition is true, print the second division
17. Console.WriteLine(" Second division")
18. ElseIf (per >= 50) Then
19. 'if ElseIf condition is true, print the third division
20. Console.WriteLine(" Third division")
21. ElseIf (per >= 40) Then
22. 'if ElseIf condition is true, print only pass with grace
23. Console.WriteLine(" Only Pass with Grace")
24. Else
25. 'if none of the condition is true, print the Failed
26. Console.WriteLine(" Failed")
27. End If
28. Console.WriteLine("press any key to exit...")
29. Console.ReadKey()
30. End Sub
31.
32. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:
Select Case Statement
In VB.NET, the Select Case statement is a collection of multiple case
statements, which allows executing a single case statement from the list
of statements. A selected case statement uses a variable to test for
equality against multiple cases or statements in a program. If the variable
is matched with any test cases, that statement will be executed. And if the
condition is not matched with any cases, it executes the default
statement.

Using the select case statement in VB.NET programming, you can replace
the uses of multiple If-Then-Else If statement from the program for better
readability and easy to use.

Syntax

Following is the syntax of the Select Case statement in VB.NET, as follows:

1. Select Case [variable or expression]


2. Case value1 'defines the item or value that you want to match.
3. // Define a statement to execute
4.
5. Case value2 'defines the item or value that you want to match.
6. // Define a statement to execute
7.
8. Case Else
9. // Define the default statement if none of the conditions is true.
10. End Select

Furthermore, you can also set more than one condition in a single case
statement, such as:

1. Select Case Variable / expression


2. Case value1
3. Statement1
4.
5. Case value2, value3
6. Statement2
7.
8. Case Else
9. // define the default statement if none of the condition is true
10. End Select

Flowchart of Select Case Statement

The following flowchart represents the functioning of the Select case


statement in the VB.NET programming language.

In Flowchart, the Select Case statement represents the evaluating of the


process start from top to bottom. If the expression or value is matched
with the first select case, statement -1 is executed else the control
transfer to the next case for checking whether the expression is matching
or not. Similarly, it checks all Select case statements for evaluating. If
none of the cases are matched, the Else block statement will be executed,
and finally, the Select Case Statement will come to an end.

Example 1: Write a program to display the Days name using the select
case statement in VB.NET.

Select_case.vb

1. Imports System
2. Module Select_case
3. Sub Main()
4. 'define a local variable.
5. Dim Days As String
6. Days = "Thurs"
7. Select Case Days
8. Case "Mon"
9. Console.WriteLine(" Today is Monday")
10. Case "Tue"
11. Console.WriteLine(" Today is Tuesday")
12. Case "Wed"
13. Console.WriteLine("Today is Wednesday")
14. Case "Thurs"
15. Console.WriteLine("Today is Thursday")
16. Case "Fri"
17. Console.WriteLine("Today is Friday")
18. Case "Sat"
19. Console.WriteLine("Today is Saturday")
20. Case "Sun"
21. Console.WriteLine("Today is Sunday")
22. Case Else
23. Console.WriteLine(" You have typed Something wron
g")
24.
25. End Select
26. Console.WriteLine("You have selected : {0}", Days)
27. Console.WriteLine("Press any key to exit...")
28. Console.ReadLine()
29. End Sub
30. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:

In the select case statement, the value of Days "Thurs" will compare all
the available select cases' values in a program. If a value matched with
any condition, it prints the particular statement, and if the value is not
matched with any select case statement, it prints the default message.

Example 2: Write a program to perform an arithmetic operation using the


Select case statement in VB.NET.

Operation.vb

Operation.vb

1. Imports System
2. Module Operation
3. Sub main()
4. 'declaration of the variables
5. Dim num1, num2, sum As Integer
6. Dim def As Char
7. 'initialization of num1 and num2 variable
8. num1 = 2
9. num2 = 6
10. Console.WriteLine(" Want to perform any operation?")
11. Console.WriteLine(" A for Addition")
12. Console.WriteLine(" S for Subtraction")
13. Console.WriteLine(" M for Multiplication")
14. Console.WriteLine(" D for Division")
15. Console.WriteLine(" Please enter any input")
16. def = Console.ReadLine()
17. Select Case def
18. Case "A"
19. 'perform Addition
20. sum = num1 + num2
21. Console.WriteLine(" Addition of two number is :{0}",
sum)
22. Case "S"
23. 'perform Subtraction
24. sum = num2 - num1
25. Console.WriteLine(" Subtraction of two number is :
{0}", sum)
26. Case "M"
27. 'perform Multiplication
28. sum = num1 * num2
29. Console.WriteLine(" Multiplication of two number is :
{0}", sum)
30. Case "D"
31. 'Peform Division
32. sum = num2 / num1
33. Console.WriteLine(" Division of two number is :{0}",
sum)
34. Case Else
35. 'If none of the operation matched, call default state
ment
36. Console.WriteLine(" Please enter only define operati
on With Capital letter")
37. End Select
38. Console.WriteLine("Press any key to exit...")
39. Console.ReadKey()
40. End Sub
41. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:
In the above example, we defined Select with multiple case statements,
and if the user-defined input is matched with any defined case
statement, it executes that statement. And if the condition is not matched
with any case, it executes a default statement in VB.NET.

Here, we provide 'M' as input, which checks all case statements, and if
any case is matched with M, it executes the statement within the
respective Case statement.

VB.NET Nested Select Case statements


When a Select Case statement is written inside the body of
another Select Case statem

ent is called a nested Select Case statement.

Syntax:

1. Select Case "num"


2. ' code to be executed if num = 1
3. Case 1
4. ' nested Select case
5. Select Case n
6.
7. ' code to be executed if n = 5
8. Case 5
9. Statement 1
10.
11. ' code to be executed if n = 10
12. Case 10
13. Statement 2
14.
15. ' code to be executed if n = 15
16. Case 15
17. Statement 3
18.
19. ' code to be executed if n doesn't match wi
th any cases.
20. Case Else
21. Statement
22.
23. ' code to be executed if num = 2
24. Case 2
25. Statement 2
26.
27. ' code to be executed if num = 3
28. Case 3
29. Statement 3
30.
31. ' code to be executed if num doesn't match with any c
ases.
32. Case Else
33. Statement

Example 1: Write a program to use a nested select case statement in


VB.NET.

Module1.vb

1. Module Module1
2.
3. Sub Main()
4.
5. Dim x As Integer = 10, y As Integer = 5
6. Select Case x
7.
8. Case 10
9. Console.WriteLine("X Value: 10")
10.
11.
12. Select Case y
13. Case 5
14. Console.WriteLine("Nested Switch Value: 5")
15.
16.
17. Select Case y - 2
18. Case 3
19. Console.WriteLine("Another Nested Switch
Value: 3")
20.
21. End Select
22. End Select
23.
24. Case 15
25. Console.WriteLine("X Value: 15")
26.
27. Case 20
28. Console.WriteLine("X Value: 20")
29.
30. Case Else
31. Console.WriteLine("Not Known")
32.
33. End Select
34. Console.WriteLine("Press Enter Key to Exit..")
35. Console.ReadLine()
36. End Sub
37. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:

Example 2: Write a program to use the nested select case statement in


VB.NET.
nested_selectcase.vb

1. Imports System
2. Module nested_selectcase
3. Sub Main()
4. Dim num As Integer
5. Dim str As String
6. str = "F"
7.
8. Console.WriteLine(" Enter only First three number like 1, 2, 3")
9. num = Console.ReadLine() 'take input from the user
10. Select Case num
11. Case 1
12. Console.WriteLine(" You are in block 1")
13. Console.WriteLine("Only First two letter such as A an
d B")
14.
15. str = Console.ReadLine()
16. Select Case str
17. Case "A", "a"
18. Console.WriteLine(" This is a VB.NET Tutorial")
19. Case "B", "b"
20. Console.WriteLine(" Welcome to the JavaTpoint
")
21. Case Else
22. Console.WriteLine(" Something is wrong")
23. End Select
24.
25. Case 2
26. Console.WriteLine(" You are in block 2")
27. Console.WriteLine("Only First two letter such as C an
d D")
28. str = Console.ReadLine()
29. Select Case str
30. Case "C", "c"
31. Console.WriteLine(" Welcome to the World!")
32. Case "D", "d"
33. Console.WriteLine(" Want to go in Heaven")
34. Case Else
35. Console.WriteLine(" Something is wrong")
36. End Select
37.
38. Case 3
39. Console.WriteLine(" You are in block 3")
40. Console.WriteLine("Only First two letter such as E an
d F")
41. str = Console.ReadLine()
42. Select Case str
43. Case "E", "e"
44. Console.WriteLine(" VB.NET is a programming l
anguage to develop web, window, and console-based application. ")
45. Case "F", "f"
46. Console.WriteLine(" You have to basic knowled
ge of c and c++")
47. Case Else
48. Console.WriteLine(" Something is wrong")
49. End Select
50. Case Else
51. Console.WriteLine(" Something is wrong")
52. End Select
53. Console.ReadLine()
54. End Sub
55. End Module

Now compile and execute the above program by clicking on the Start or
F5 button, it shows the following output:

VB.NET Do Loop
A Loop is used to repeat the same process multiple times until it meets the
specified condition in a program. By using a loop in a program, a programmer
can repeat any number of statements up to the desired number of repetitions. A
loop also provides the suitability to a programmer to repeat the statement in a
program according to the requirement. A loop is also used to reduce the
program complexity, easy to understand, and easy to debug.
Advantages of VB.NET loop
o It provides code iteration functionality in a program.
o It executes the statement until the specified condition is true.
o It helps in reducing the size of the code.
o It reduces compile time.
Types of Loops
There are five types of loops available in VB.NET:
o Do While Loop
o For Next Loop
o For Each Loop
o While End Loop
o With End Loop
Do While Loop
In VB.NET, Do While loop is used to execute blocks of statements in the
program, as long as the condition remains true. It is similar to the While End
Loop, but there is slight difference between them. The while loop initially
checks the defined condition, if the condition becomes true, the while loop's
statement is executed. Whereas in the Do loop, is opposite of the while loop, it
means that it executes the Do statements, and then it checks the condition.
Syntax:
1. Do
2. [ Statements to be executed]
3. Loop While Boolean_expression
4. // or
5. Do
6. [Statement to be executed]
7. Loop Until Boolean_expression
In the above syntax, the Do keyword followed a block of statements,
and While keyword checks Boolean_expression after the execution of the first
Do statement.
Flowchart of Do loop

The above flow chart represents the flow of Do While loop. It is used to control
the flow of statements, such that it executes the statement at least once before
checking the While or Until condition. If the condition is true, the next iteration
will be executed till the condition become false.
Example 1. Write a simple program to print a number from 1 to 10 using the Do
While loop in VB.NET.
Do_loop.vb
1. Imports System
2. Module Do_loop
3. Sub Main()
4. ' Initializatio and Declaration of variable i
5. Dim i As Integer = 1
6. Do
7. ' Executes the following Statement
8. Console.WriteLine(" Value of variable I is : {0}", i)
9. i = i + 1 'Increment the variable i by 1
10. Loop While i <= 10 ' Define the While Condition
11.
12. Console.WriteLine(" Press any key to exit...")
13. Console.ReadKey()
14. End Sub
15.End Module
Now compile and execute the above program by clicking on the Start button, it
shows the following output:

In the above program, the Do While loop executes the body until the given
condition becomes false. When the condition becomes false the loop will be
terminated.
Use of Until in Do Until Loop statement
In the VB.NET loop, there is a Do Until loop statement, which is similar to
the Do While loop. The Do Statement executes as long as Until condition
becomes true.
Example: Write a program to understand the uses of Do Until Loop in VB.NET.
Do_loop.vb
1. Imports System
2. Module Do_loop
3. Sub Main()
4. ' Initialization and Declaration of variable i
5. Dim i As Integer = 1
6. Do
7. ' Executes the following Statement
8. Console.WriteLine(" Value of variable i is : {0}", i)
9. i = i + 1 'Increment variable i by 1
10. Loop Until i = 10 ' Define the Until Condition
11.
12. Console.WriteLine(" Press any key to exit...")
13. Console.ReadKey()
14. End Sub
15.End Module
Output:

In the above program, a Do Until loop is executed their statement until the given
condition Until (i =10) is not meet. When the counter value of the variable
i becomes 10, the defined statement will be false, and the loop will be
terminated.
Nested Do While Loop Statement
In VB.NET, when we use one Do While loop inside the body of another Do
While loop, it is called Nested Do While loop.
Syntax
1. Do
2. // Statement of the outer loop
3. Do
4. // Statement of outer loop
5. While (condition -2)
6. // Statement of outer loop
7. While (condition -1)
Example 2: Write a simple program to use the Do While loop Statement in
VB.NET.
Nest_Do_While.vb
1. Imports System
2. Module Nest_Do_While
3. Sub Main()
4. ' Declare i and j as Integer variable
5. Dim i As Integer = 1
6. Do
7. ' Outer loop statement
8. Console.WriteLine(" Execution of Outer loop is {0}", i & " times"
)
9.
10. Dim j As Integer = 1
11.
12. Do
13. 'Inner loop statement
14. Console.WriteLine(" Execution of Inner loop is {0}", j)
15. j = j + 1 ' Increment Inner Counter variable by 1
16. Loop While j < 3
17.
18. Console.WriteLine()
19. i = i + 1 ' Increment Outer Counter variable by 1
20. Loop While i < 4
21. Console.WriteLine(" Exit from the loop")
22. Console.WriteLine(" Press any key to exit...")
23. Console.ReadKey()
24. End Sub
25.End Module
Output:

In the above example, each iteration of the outer loop also executes the inner
loop repeatedly until the inner condition becomes false. When the condition of
the outer loop becomes false, the execution of the outer and inner loop will be
terminated.
For Next Loop
A For Next loop is used to repeatedly execute a sequence of code or a block of
code until a given condition is satisfied. A For loop is useful in such a case when
we know how many times a block of code has to be executed. In VB.NET, the
For loop is also known as For Next Loop.
Syntax
1. For variable_name As [ DataType ] = start To end [ Step step ]
2. [ Statements to be executed ]
3. Next
Let's understand the For Next loop in detail.
o For: It is the keyword that is present at the beginning of the definition.
o variable_name: It is a variable name, which is required in the For loop
Statement. The value of the variable determines when to exit from
the For-Next loop, and the value should only be a numeric.
o [Data Type]: It represents the Data Type of the variable_name.
o start To end: The start and end are the two important parameters
representing the initial and final values of the variable_name. These
parameters are helpful while the execution begins, the initial value of the
variable is set by the start. Before the completion of each repetition, the
variable's current value is compared with the end value. And if the value
of the variable is less than the end value, the execution continues until the
variable's current value is greater than the end value. And if the value is
exceeded, the loop is terminated.
o Step: A step parameter is used to determine by which the counter value
of a variable is increased or decreased after each iteration in a program. If
the counter value is not specified; It uses 1 as the default value.
o Statements: A statement can be a single statement or group of statements
that execute during the completion of each iteration in a loop.
o Next: In VB.NET a Next is a keyword that represents the end of the For
loop's
Flowchart of For Next loop
The following flowchart represents the functioning of the For Next loop in
the VB.NET programming language.
In the above flow chart, the first step is to initialize the variable name with the
start value. And then, the value of the variable will be compared to the end
expression or value. If the condition is true, the control enters the loop body and
executes the statements. After that, the value of a variable will be automatically
incremented by the compiler. Upon completion of each iteration, the current
value of a variable will be again compared to the end expression. If the
condition is not true, the controlled exit from the loop.
Example 1. Write a simple program to print the number from 1 to 10 using the
For Next loop.
Number.vb
1. Imports System
2. Module Number
3. Sub Main()
4. ' It is a simple print statement, and 'vbCrLf' is used to jump in the ne
xt line.
5. Console.Write(" The number starts from 1 to 10 " & vbCrLf)
6. ' declare and initialize variable i
7. For i As Integer = 1 To 10 Step 1
8. ' if the condition is true, the following statement will be executed
9. Console.WriteLine(" Number is {0} ", i)
10. ' after completion of each iteration, next will update the variable c
ounter
11. Next
12. Console.WriteLine(" Press any key to exit... ")
13. Console.ReadKey()
14. End Sub
15.End Module
Output:

In the above example, we have initialized an integer variable i with an initial


value 1. The For loop will continuously execute its body until the value of i is
smaller or equal to 10. After each iteration, the value of i is automatically
increased with 'Step 1'. If the value of i reached 10, the loop would
be terminated and control transfer to the Main() function.
Further, we can change the Step in For Next loop. Write the following program
to skip the number is 2.
Number.vb
1. Imports System
2. Module Number
3. Sub Main()
4. ' declaration of variable i
5. Dim i As Integer
6. Console.Write(" Skip one number at the completion of each iteration
in between 1 to 10 " & vbCrLf)
7. ' initialize i to 1 and declare Step to 2 for skipping a number
8. For i = 1 To 10 Step 2
9. ' if condition is true, it skips one number
10. Console.WriteLine(" Number is {0} ", i)
11. ' after completion of each iteration, next will update the variable c
ounter to step 2
12. Next
13. Console.WriteLine(" Press any key to exit... ")
14. Console.ReadKey()
15. End Sub
16.End Module
Output:

As we can see in the above output, the value of the variable i is initialized with
1, and the value of i is skipped by 'Step 2' in the loop for each iteration to
print the skipped number from 1 to 10.
Example 2: Write a simple program to print a table in the VB.NET.
Table.vb
1. Imports System
2. Module Table
3. Sub Main()
4. 'declaration of i and num variable
5. Dim i, num As Integer
6. Console.WriteLine(" Enter any number to print the table")
7. num = Console.ReadLine() ' accept a number from the user
8. Console.WriteLine(" Table of " & num)
9. 'define for loop condition, it automatically initialize step to 1
10. For i = 1 To 10
11. Console.WriteLine(num & " * " & i & " = " & i * num)
12. Next
13. Console.ReadKey()
14. End Sub
15.End Module
Output:

Nested For Next Loop in VB.NET


In VB.NET, when we write one For loop inside the body of another For Next
loop, it is called Nested For Next loop.
Syntax:
1. For variable_name As [Data Type] = start To end [ Step step ]
2. For variable_name As [Data Type] = start To end [ Step step ]
3. [ inner loop statements ]
4. Next
5. [ Outer loop statements ]
6. Next
Following is the example of Nested For Next loop in VB.NET.
Nested_loop.vb
1. Imports System
2. Module Nested_loop
3. Sub Main()
4. Dim i, j As Integer
5. For i = 1 To 3
6. 'Outer loop
7. Console.WriteLine(" Outer loop, i = {0}", i)
8. 'Console.WriteLine(vbCrLf)
9.
10. 'Inner loop
11. For j = 1 To 4
12. Console.WriteLine(" Inner loop, j = {0}", j)
13. Next
14. Console.WriteLine()
15. Next
16. Console.WriteLine(" Press any key to exit...")
17. Console.ReadKey()
18. End Sub
19.End Module
Output:
In the above example, at each iteration of the outer loop, the inner loop is
repeatedly executed its entire cycles until the condition is not satisfied.
Example 2: Write a program to print a pattern in VB.NET.
Pattern.vb
1. Imports System
2. Module Pattern
3. Sub Main()
4. Dim i, n, j As Integer
5. Console.WriteLine(" Enter a number to show rows in a Pattern")
6. ' take a number from user
7. n = Console.ReadLine()
8.
9. 'Outer loop
10. For i = 1 To n
11. 'Inner loop
12. 'value of j should be less than i
13. For j = 1 To i
14. Console.Write(" * ")
15. Next
16. Console.WriteLine("")
17. Next
18. Console.WriteLine(" Press any key to exit...")
19. Console.ReadKey()
20. End Sub
21.End Module
Output:

VB.NET For Each Loop


In the VB.NET, For Each loop is used to iterate block of statements in an array
or collection objects. Using For Each loop, we can easily work with collection
objects such as lists, arrays, etc., to execute each element of an array or in a
collection. And when iteration through each element in the array or collection is
complete, the control transferred to the next statement to end the loop.
Syntax:
1. For Each var_name As [ DataType ] In Collection_Object
2. [ Statements to be executed]
3. Next
For Each loop is used to read each element from the collection object or an
array. The Data Type represents the type of the variable, and var_name is the
name of the variable to access elements from the array or collection object so
that it can be used in the body of For Each loop.
Flowchart of For Each loop
The following flowchart represents the For Each Next loop's functioning to
iterate through array elements in the VB.NET programming language.

The first step is to initialize an array or collection object to execute each


element of the array with the help of variables in For Each loop. A variable is
used in For Each loop to checks whether the element is available or not. If the
element is available in the collection object, the For Each block will be executed
until the condition remains true. After the execution of each element of an array,
the control transfer to the end statement.
Examples of For Each Loop
Write a simple program to understand the uses of For Each Next loop in
VB.NET.
For_Each_loop.vb
1. Imports System
2. Module For_Each_loop
3. Sub Main()
4. 'declare and initialize an array as integer
5. Dim An_array() As Integer = {1, 2, 3, 4, 5}
6. Dim i As Integer 'Declare i as Integer
7.
8. For Each i In An_array
9. Console.WriteLine(" Value of i is {0}", i)
10. Next
11. Console.WriteLine("Press any key to exit...")
12. Console.ReadLine()
13. End Sub
14.End Module
Output:

In the above example, we create an integer array with the name An_array (),
and For Each loop is used to iterate each element of the array with the help of
defined variable 'i'.
Example 2: Write a simple program to print fruit names using For Each loop in
VB.NET.
For_each.vb
1. Imports System
2. Module For_each
3. Sub Main()
4. 'Define a String array
5. Dim str() As String
6.
7. 'Initialize all element of str() array
8. str = {"Apple", "Orange", "Mango", "PineApple", "Grapes", "Banan
a"}
9.
10. Console.WriteLine("Fruit names are")
11.
12. 'Declare variable name as fruit
13. For Each fruit As String In str
14. Console.WriteLine(fruit)
15. Next
16. Console.WriteLine(" Press any key to exit...")
17. Console.ReadKey()
18. End Sub
19.End Module
Output:

In this example, str() is a String type array that defines different fruits names.
And fruit is the name of a variable that is used to iterate each element of
the str() array using For Each loop in the program. If all the element is read,
control passes to the Main() function to terminate the program.
VB.NET While End Loop
The While End loop is used to execute blocks of code or statements in a
program, as long as the given condition is true. It is useful when the number of
executions of a block is not known. It is also known as an entry-controlled
loop statement, which means it initially checks all loop conditions. If the
condition is true, the body of the while loop is executed. This process of
repeated execution of the body continues until the condition is not false. And if
the condition is false, control is transferred out of the loop.
Syntax:
1. While [condition]
2. [ Statement to be executed ]
3. End While
Here, condition represents any Boolean condition, and if the logical condition
is true, the single or block of statements define inside the body of the while
loop is executed.
Flow Diagram of the While End Loop in VB.NET
As we know, the While End loop is an entry-controlled loop used to determine
if the condition is true, the statements defined in the body of the loop are
executed, and the execution process continues till the condition is satisfied.
Furthermore, after each iteration, the value of the counter variable is
incremented. It again checks whether the defined condition is true; And if the
condition is again true, the body of the While loop is executed. And when the
condition is not true, the control transferred to the end of the loop.
Example: Write a simple program to print the number from 1 to 10 using while
End loop in VB.NET.
while_number.vb
1. Imports System
2. Module while_number
3. Sub Main()
4. 'declare x as an integer variable
5. Dim x As Integer
6. x=1
7. ' Use While End condition
8. While x <= 10
9. 'If the condition is true, the statement will be executed.
10. Console.WriteLine(" Number {0}", x)
11. x = x + 1 ' Statement that change the value of the condition
12. End While
13. Console.WriteLine(" Press any key to exit...")
14. Console.ReadKey()
15. End Sub
16.End Module
Output:
In the above example, while loop executes its body or statement up to the
defined state (i <= 10). And when the value of the variable i is 11, the defined
condition will be false; the loop will be terminated.
Example 2: Write a program to print the sum of digits of any number using
while End loop in VB.NET.
Total_Sum.vb
1. Public Class Total_Sum ' Create a Class Total_sum
2. Shared Sub Main()
3. 'Declare an Integer variable
4. Dim n, remainder, sum As Integer
5. sum = 0
6.
7. Console.WriteLine(" Enter the number :")
8. n = Console.ReadLine() ' Accept a number from the user
9.
10. ' Use While loop and write given below condition
11. While (n > 0)
12. remainder = n Mod 10
13. sum += remainder
14. n = n / 10
15. End While
16. Console.WriteLine(" Sum of digit is :{0}", sum)
17. Console.WriteLine(" Press any key to exit...")
18. Console.ReadKey()
19. End Sub
20.End Class
Output:

Nested While End Loop


In VB.NET, when we write a While End loop inside the body of another While
End loop, it is called Nested While End loop.
Syntax
1. While (condition -1)
2. // body of the outer while loop
3. While (condition -2)
4. // body of inner while loop
5. End While
6. // body of the outer loop
7. End While
Write a program to understand the Nested While End loop in VB.NET
programming.
Nest_While.vb
1. Imports System
2. Module Nest_While
3. Sub Main()
4. ' Declare i and j as Integer variable
5. Dim i As Integer = 1
6.
7.
8. While i < 4
9. ' Outer loop statement
10. Console.WriteLine(" Counter value of Outer loop is {0}", i)
11. Dim j As Integer = 1
12.
13. While j < 3
14. 'Inner loop statement
15. Console.WriteLine(" Counter value of Inner loop is {0}", j)
16. j = j + 1 ' Increment Inner Counter variable by 1
17. End While
18. Console.WriteLine() 'print space
19. i = i + 1 ' Increment Outer Counter variable by 1
20. End While
21. Console.WriteLine(" Press any key to exit...")
22. Console.ReadKey()
23. End Sub
24.End Module
Output:
In the above example, at each iteration of the outer loop, the inner loop is
repeatedly executed its entire cycles until the inner condition is not satisfied.
And when the condition of the outer loop is false, the execution of the outer and
inner loop is terminated.
VB.NET With End With Statement
In VB.NET, the With End statement is not the same as a loop structure. It is
used to access and execute statements on a specified object without specifying
the name of the objects with each statement. Within a With statement block,
you can specify a member of an object that begins with a period (.) to define
multiple statements.
Syntax:
1. With objExpression
2. [ Statements to be Executed]
3. End With
objExpression: It defines the data type of objExpression. It may be any class
or structure type or basic data type such as Integer. It can be executed once in
the With End statement.
Statement: It defines one or more executed statements within the With block.
The statement refers to the member of the object that links
with objectExpression to execute the With statement block.
End With: It is used to end the With block.
Example: Write a program to understand the uses of With End statement
in VB.NET.
Employee.vb
1. Public Class Employee
2. ' definition of global variables
3. Public Property name As String
4. Public Property age As Integer
5. Public Property Occupation As String
6. Public Property email As String
7.
8. Shared Sub Main()
9. ' Create an emp object
10. Dim emp As New Employee
11. ' To define the member of an object
12. With emp
13. .name = " Mr. Stephen"
14. .age = 33
15. .Occupation = "Data Analyst"
16. .email = "[email protected]"
17. End With
18. With emp
19. ' use emp as a reference
20. Console.WriteLine(" Name is : {0}", .name)
21. Console.WriteLine(" Age is : {0}", .age)
22. Console.WriteLine(" Occupation is : {0}", .Occupation)
23. Console.WriteLine(" Employee Email is : {0}", .email)
24. End With
25. Console.WriteLine(" Press any key to exit...")
26. Console.ReadKey()
27. End Sub
28.End Class
Output:

Example: Write a program to display the student details using the With End
statement in VB.NET.
With_Statement.vb
1. Imports System
2. Module With_statement
3. Sub Main()
4. ' Create a stud object
5. Dim stud As Student = New Student()
6.
7. ' To define the member of an object using With Statement
8. With stud
9. .stud_name = " Mr. Robert"
10. .stud_course = "Computer Science"
11. .stud_rollno = "01"
12. End With
13.
14. With stud
15. ' use stud as a reference
16. Console.WriteLine(" Student Name is : {0}", .stud_name)
17. Console.WriteLine(" Student Course Name is : {0}", .stud_course
)
18. Console.WriteLine(" Student RollNo. is : {0}", .stud_rollno)
19. End With
20. Console.WriteLine(" Press any key to exit...")
21. Console.ReadKey()
22. End Sub
23.
24. ' Create a Class Student
25. Public Class Student
26. Public stud_name As String 'Define the variable of a class
27. Public stud_course As String
28. Public stud_rollno As Integer
29. End Class
30.End Module
Output:

VB.NET Exit Statement


In VB.NET, the Exit statement is used to terminate the loop (for, while, do,
select case, etc.) or exit the loop and pass control immediately to the next
statement of the termination loop. Furthermore, the Exit statement can also be
used in the nested loop to stop or terminate the execution of the inner or outer
loop at any time, depending on our requirements.
Syntax
1. Exit { Do | For | Function | Property | Select | Sub | Try | While }
The flow of Exit Statement
Following is the diagrammatical representation of Exit Statement in VB.NET
programming language.

Generally, the Exit statement is written along with a condition. If


the Exit condition is true inside the loop, it exits from the loop and control
transfer to the next statement, followed by the loop. And if the Exit condition
fails for the first time, it will not check any statement inside the loop
and terminates the program.
We will now see how to use the Exit statement in loops and Select case
statements to finish the program's execution in the VB.NET programming
language.
Advertisement
Use of Exit statement in While End loop
Example 1: Write a simple program to use the Exit Statement in While End
loop.
Exit_While.vb
1. Imports System
2. Module Exit_While
3. Sub Main()
4. ' Definition of count variable
5. Dim count As Integer = 1
6.
7. ' Execution of While loop
8. While (count < 10)
9. ' Define the Exit condition using If statement
10. If count = 5 Then
11. Exit While ' terminate the While loop
12. End If
13. Console.WriteLine(" Value of Count is : {0}", count)
14. count = count + 1
15. End While
16. Console.WriteLine(" Exit from the While loop when count = {0}", c
ount)
17. Console.WriteLine(" Press any key to exit...")
18. Console.ReadKey()
19. End Sub
20.End Module
Output:

In the above example, the While End loop is continuously executed, its body
until the given condition While (count < 10) is not satisfied. But when
the Exit condition (count = 5) falls inside a while loop, the execution of the
loop is automatically terminated, and control moves to the next part of the loop
statement.
Use of Exit statement in For Next loop
Example 2: Write a program to calculate the sum of 10 numbers, and if a
negative number is entered, the For Each loop ends.
1. Imports System
2. Module Exit_For
3. Sub Main()
4. 'Definition of num variable
5. Dim num As Integer
6. Dim sum As Double = 0.0
7.
8. 'Execution of For loop
9. For i As Integer = 1 To 10
10. 'Accept a number from the user
11. Console.WriteLine("Enter a number : ")
12. num = Console.ReadLine()
13. ' If the user enters a negative number, the loop terminates
14. If num < 0 Then
15. Exit For ' terminate the For loop
16. End If
17. sum += num
18. Next
19.
20. Console.WriteLine(" Exit from the For loop when (num < 0) is: {0}"
, num)
21. Console.WriteLine(" Total sum is : {0}", sum)
22. Console.WriteLine(" Press any key to exit from the Console Screen"
)
23. Console.ReadKey()
24. End Sub
25.End Module
Output:

The above program accepts a number from the user until it encounters a
negative or less than 0 (num < 0). And when there is a negative number,
the Exit statement terminates the loop, and the control transfer to the next part
of the loop.
Use of Exit statement in Do While loop
Example 3: Write a simple program to use the Exit Statement in Do While
Loop.
Exit_Do_While.vb
1. Imports System
2. Module Exit_Do_While
3. Sub Main()
4. 'Definition of the count variable
5. Dim count As Integer = 20
6.
7. ' Definition of Do While loop
8. Do
9. 'Define the Exit condition using If statement.
10.
11. If count = 25 Then
12. Exit Do ' terminate the Do While loop
13. End If
14. Console.WriteLine(" Value of Count is : {0}", count)
15. count = count + 1
16. Loop While (count < 50)
17. Console.WriteLine(" Exit from the Do While loop when count = {0}
", count)
18. Console.WriteLine(" Press any key to exit...")
19. Console.ReadKey()
20. End Sub
21.End Module
Output:

In the above example, the Do While loop is continuously executed, its body
until the given condition While (count < 50) is not satisfied. But when
the Exit condition (count = 25) is encountered, the Do While loop is
automatically terminated. The control is immediately transferred to the next
statement, followed by the loop statements.
VB.NET Continue Statement
In VB.NET, the continue statement is used to skip the particular iteration of the
loop and continue with the next iteration. Generally, the continue Statement is
written inside the body of the For, While and Do While loop with a condition. In
the previous section, we learned about the Exit Statement. The main difference
between the Exit and a Continue Statement is that the Exit Statement is used to
exit or terminate the loop's execution process. In contrast, the Continue
Statement is used to Skip the particular iteration and continue with the next
iteration without ending the loop.
Syntax:
1. Continue { Do | For | While }
Flow Diagram of Continue Statement
Following is the pictorial representation of the Continue Statement in VB.NET
programming language.

In the above diagram, a Continue Statement is placed inside the loop to skip a
particular statement or iteration. Generally, a continue statement is used with
a condition. If the condition is true, it skips the particular iteration and
immediately transfers the control to the beginning of the loop for the execution
of the next iteration.
Now we will see how to use the Continue statement in the loop to skip the
execution of the code and send the control to the beginning of the loop to
execute further statements in the VB.NET programming language.
Use of Continue statement in While End loop
Example 1: Write a simple program to use the Continue Statement in While
End loop.
Continue_While.vb
1. Imports System
2. Module Continue_While
3. Sub Main()
4. 'Declaration and initialization of variable i
5. Dim i As Integer = 10
6.
7. 'Define the While Loop Condition
8. While i < 20
9.
10. If i = 14 Then
11. Console.WriteLine(" Skipped number is {0}", i)
12. i += 1 ' skip the define iteration
13. Continue While
14. End If
15. Console.WriteLine(" Value of i is {0}", i)
16.
17. i += 1 ' Update the variable i by 1
18. End While
19. Console.WriteLine(" Press any key to exit...")
20. Console.ReadKey()
21. End Sub
22.End Module
Output:
In the above program, the While loop is continuously executed, their body until
the given condition ( i < 20) is met. But when the value of i is equal to 15, the
Continue statement is encountered. It skips the current execution and transfers
the control to the beginning of the loop to display the next iteration.
Use of Continue statement in For Next loop
Example 2: Write a simple program to print the number from 10 to 1 with
Continue Statement in For Next loop.
Continue_For.vb
1. Imports System
2. Module Continue_For
3. Sub Main()
4. 'Declaration and initialization of variable i, num
5. Dim i As Integer = 10
6. Dim num As Integer
7. 'Define the For Loop Condition
8. For i = 10 To 1 Step -1
9.
10. If i = 5 Then ' if i = 5, it skips the iteration
11. num = i 'Assign the skip value to num variable
12. Continue For ' Continue with Next Iteration
13. End If
14. Console.WriteLine(" Value of i is {0}", i)
15.
16. Next
17. Console.WriteLine(" Skipped number is {0}", num)
18. Console.WriteLine(" Press any key to exit...")
19. Console.ReadKey()
20. End Sub
21.End Module
Output:

In the above program, the For loop is continuously decremented their body until
the variable i is 1. But when the value of i is equal to 5, the Continue Statement
is encountered. Then it skips the current execution and transfers control to the
beginning of the loop to display the next iteration.
Use of Continue statement in Do While loop
Example 3: Write a simple program to Understand the use of Continue
Statement in Do While loop.
Continue_Do_While.vb
1. Imports System
2. Module Continue_Do_While
3. Sub Main()
4. 'Declaration and initialization of local variable
5. Dim i As Integer = 10, num As Integer
6.
7. 'Definition the Do While Loop
8. Do
9. If i = 14 Then
10. num = i
11. i += 1 ' skip the define iteration
12. Continue Do
13. End If
14. Console.WriteLine(" Value of i is {0}", i)
15.
16. i += 1 ' Update the variable i by 1
17. Loop While i < 20
18. Console.WriteLine(" Skipped number is {0}", num)
19.
20. Console.WriteLine(" Press any key to exit...")
21. Console.ReadKey()
22. End Sub
23.End Module
Output:

In the above program, the Do loop is continuously executed their body until the
given condition ( i < 20) is met. But when the value of i is equal to 15, the
Continue Statement is encountered. It skips the current execution and transfers
the control to the beginning of the loop to display the next iteration.
VB.NET GoTo Statement
In VB.NET, the GoTo statement is known as a jump statement. It is a control
statement that transfers the flow of control to the specified label within the
procedure. The GoTo statement uses labels that must be a valid identifier. The
GoTo statement can be used in Select case, decision control statements, and
loops.
Syntax:
1. GoTo label_1
Here, GoTo is a keyword, and label_1 is a label used to transfer control to a
specified label statement in a program.
Now we will see how to use the GoTo statement in the loop, select case, or
decision-making statement to transfer control to the specified label statement in
the VB.NET program.
Use of GoTo statement in If Else
Example 1: Write a simple program to print whether the number is even or odd
in GoTo Statement.
Goto_Statement.vb
1. Imports System
2. Module Goto_Statement
3. Sub Main()
4. 'Declaration of local variable
5. Dim num As Integer
6. Console.WriteLine(" Enter the number :")
7. num = Console.ReadLine ' Accept a number from the user
8. If (num Mod 2 = 0) Then
9. GoTo even ' Jump to even label
10. Else
11. GoTo odd ' Jump to odd label
12. End If
13.odd:
14. Console.WriteLine(" It is an Odd number")
15.
16.even:
17. Console.WriteLine(" It is an Even number ")
18. Console.WriteLine(" Press any key to exit...")
19. Console.ReadKey()
20. End Sub
21.End Module
Output:

In the above program, when we enter a number, it checks whether the number is
even or odd. And if the number is odd, the GoTo statement will be encountered,
and the control transfers to the odd statement Else the control transfer to
the even statement.
Use of GoTo Statement in For Next loop
Example 2: Write a program to print the sum of the First ten numbers using the
Goto Statement in VB.NET.
Goto_For.vb
1. Imports System
2. Module Goto_For
3. Sub Main()
4. 'Declaration of local variable
5. Dim i, n As Integer, Sum As Integer = 0
6.
7. ' Define For Loop Statement
8. For i = 1 To 10
9. Console.WriteLine(" Value of i is {0}", i)
10. Sum = Sum + i 'At each iteration the value of i added to Sum
11. If i = 5 Then
12. n = i 'Assign i to n
13.
14. GoTo total_sum ' Jump to total_sum
15. End If
16. Next
17.total_sum:
18. Console.WriteLine(" Total sum is {0}", Sum)
19. Console.WriteLine(" GoTo Encounter, when value of i = {0}", n)
20. Console.WriteLine(" Press any key to exit...")
21. Console.ReadKey()
22. End Sub
23.End Module
Output:

In the above program, the For loop is executed till the given condition ( i = 1 To
10). And when the value of i is equal to 5, the GoTo statement will be
encountered, and it transfers the control to total_sum so that the total sum of
each iteration can be printed in the For loop.
Use of GoTo statement in Select Case Statement
Example 3: Write a simple program to print the days' names in select cases
using the GoTo Statement.
Goto_Select.vb
1. Imports System
2. Module Goto_Select
3. Sub Main()
4. 'Definition of local variable
5. Dim Days As String
6. Days = "Thurs"
7. Select Case Days
8.
9. Case "Mon"
10.Case1:
11.
12. Console.WriteLine(" Today is Monday")
13. Case "Tue"
14. Console.WriteLine(" Today is Tuesday")
15. Case "Wed"
16. Console.WriteLine("Today is Wednesday")
17. Case "Thurs"
18. Console.WriteLine("Today is Thursday")
19. GoTo Case1
20. Case "Fri"
21. Console.WriteLine("Today is Friday")
22. Case "Sat"
23. Console.WriteLine("Today is Saturday")
24. Case "Sun"
25. Console.WriteLine("Today is Sunday")
26. Case Else
27. Console.WriteLine(" Something wrong")
28.
29. End Select
30. Console.WriteLine("You have selected : {0}", Days)
31. Console.WriteLine("Press any key to exit...")
32. Console.ReadLine()
33. End Sub
34.End Module
Output:

In the Select case statement, the value of Days Thurs will compare the values of
all selected cases available in a program. If it matches any statement, it prints
the particular statement and contains the GoTo statement that transfers control to
defined case1: and then the following statement is executed.
Use of GoTo statement in While End Loop Statement
Example 4: Write a simple program to understand the use of GoTo statement in
the While loop.
Goto_While.vb
1. Imports System
2. Module GoTo_While
3. Sub Main()
4. 'Declaration and initialization of the local variable
5. Dim i As Integer = 1, num As Integer
6. start1:
7. 'Definition of While Loop
8. While i < 10
9. If i = 6 Then
10. num = i
11. i += 1
12. GoTo start1 'transfer control at start1
13. End If
14. Console.WriteLine(" Value of i is {0}", i)
15.
16. i += 1 ' Update the variable i by 1
17. End While
18. Console.WriteLine(" Control transfer at number {0}", num)
19.
20. Console.WriteLine(" Press any key to exit...")
21. Console.ReadKey()
22. End Sub
23.End Module
Output:

msgbox and input box functions


MsgBox ( ) Function
The objective of MsgBox is to produce a pop-up message box that prompt the user to
click on a command button before he /she can continues. This format is as follows:
yourMsg=MsgBox(Prompt, Style Value, Title)

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

Style Value Named Constant Buttons Displayed

0 vbOkOnly Ok button

1 vbOkCancel Ok and Cancel buttons

2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.

3 vbYesNoCancel Yes, No and Cancel buttons

4 vbYesNo Yes and No buttons

5 vbRetryCancel Retry and Cancel buttons

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

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

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

are the same.

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

Named
Value Button Clicked
Constant

1 vbOk Ok button

2 vbCancel> Cancel button

3 vbAbort Abort button

4 vbRetry Retry button

5 vbIgnore Ignore button

6 vbYes Yes button

7 vbNo No button

Example 10.1
i. The Interface:

You draw three command buttons and a label as shown in Figure 10.1

Figure 10.1
The procedure for the test button:
Private Sub Test_Click()
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
Display.Caption = "Testing Successful"
Else
Display.Caption = "Testing fail"
End If

End Sub

When the user click on the test button, the image like the one shown in Figure 10.2 will
appear. As the user click on the OK button, the message "Testing successful" will be
displayed and when he/she clicks on the Cancel button, the message "Testing fail" will
be displayed.

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

Table 10.3

Value Named Constant Icon

16 vbCritical

32 vbQuestion

48 vbExclamation
64 vbInformation

Example 10.2
You draw the same Interface as in example 10.1 but modify the codes as follows:

Private Sub test2_Click()

Dim testMsg2 As Integer


testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test Message")
If testMsg2 = 6 Then
display2.Caption = "Testing successful"
ElseIf testMsg2 = 7 Then
display2.Caption = "Are you sure?"
Else
display2.Caption = "Testing fail"
End If

End Sub

In this example, the following message box will be displayed:


Figure 10.3

The InputBox( ) Function


An InputBox( ) function will display a message box where the user can enter a value or a
message in the form of text. The format is

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

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

 Prompt - The message displayed normally as a question asked.


 Title - The title of the Input Box.
 default-text - The default text that appears in the input field where users can use
it as his intended input or he may change to the message he wish to key in.
 x-position and y-position - the position or the coordinate of the input box.
Example 10.3
i. The Interface
Figure 10.4

ii. The procedure for the OK button

Private Sub OK_Click()

Dim userMsg As String


userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your
messge here", 500, 700)
If userMsg <> "" Then
message.Caption = userMsg
Else
message.Caption = "No Message"
End If

End Sub

When a user click the OK button, the input box as shown in Figure 10.5 will appear. After
user entering the message and click OK, the message will be displayed on the caption, if
he click Cancel, "No message" will be displayed.
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest

Arrays of array. Collections: Adding, Removing, Counting, Returning items in a


collection, Processing a collection.
PROCEDURES IN VISUAL BASIC 6 Visual Basic offers different types of procedures to execute
small sections of coding in applications. The various procedures are elucidated in details in
this section. Visual Basic programs can be broken into smaller logical components called
Procedures. Procedures are useful for condensing repeated operations such as the
frequently used calculations, text and control manipulation etc. The benefits of using
procedures in programming are: It is easier to debug a program a program with procedures,
which breaks a program into discrete logical limits. Procedures used in one program can act
as building blocks for other programs with slight modifications. A Procedure can be Sub,
Function or Property Procedure. Sub Procedures A sub procedure can be placed in standard,
class and form modules. Each time the procedure is called, the statements between Sub and
End Sub are executed. The syntax for a sub procedure is as follows: [Private | Public] [Static]
Sub Procedurename [( arglist)] [ statements] End Sub arglist is a list of argument names
separated by commas. Each argument acts like a variable in the procedure. There are two
types of Sub Procedures namely general procedures and event procedures. Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore (_), and the event name. The following syntax represents the event procedure
for a Form_Load event. Private Sub Form_Load() ....statement block.. End Sub Event
Procedures acquire the declarations as Private by default. General Procedures A general
procedure is declared when several event procedures perform the same actions. It is a good
programming practice to write common statements in a separate procedure (general
procedure) and then call them in the event procedure
Property Procedures A property procedure is used to create and manipulate custom
properties. It is used to create read only properties for Forms, Standard modules and Class
modules
.Visual Basic provides three kind of property procedures-Property Let procedure that sets the
value of a property, Property Get procedure that returns the value of a property, and
Property Set procedure that sets the references to an object.
ARRAYS
An array is a variable with a single name that represents many different items. When we
work with a single item, we only need to use one variable. However, if we have a list of items
which are of similar type to deal with, we need to declare an array of variables instead of
using a variable for each item For example, if we need to enter one hundred names, it is
difficult to declare 100 different names. Besides, if we want to process those data that
involves decision making, we might have to use hundreds of if...then statements, this is a
waste of time and efforts.So, instead of declaring one hundred different variables, we need
to declare only one array. We differentiate each item in the array by using subscript, the
index value of each item, for example, name(1), name(2), name(3) .......etc. , makes declaring
variables more streamline. The Individual elements of an array are identified using an index.
Arrays have upper and lower bounds and the elements have to lie within those bounds. Each
index number in an array is allocated individual memory space and therefore users must
evade declaring arrays of larger size than required. We can declare an array of any of the
basic data types including variant, user-defined types and object variables. The individual
elements of an array are all of the same data type.
Declaring arrays Arrays occupy space in memory. The programmer specifies the array type
and the number of elements required by the array so that the compiler may reserve the
appropriate amount of memory. Arrays may be declared as Public (in a code module),
module or local. Module arrays are declared in the general declarations using keyword Dim
or Private. Local arrays are declared in a procedure using Dim or Static.
Array must be declared explicitly with keyword "As". There are two types of arrays in Visual
Basic namely: Fixed-size/static array : The size of array always remains the same-size doesn't
change during the program execution. Dynamic array : The size of the array can be changed
at the run time- size changes during the program execution

VB.Net - Arrays
An array stores a fixed-size sequential collection of elements of the same
type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last
element.

Creating Arrays in VB.Net


To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For
example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
The elements in an array can be stored and accessed by using the index
of the array. The following program demonstrates this −
Live Demo

Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '

For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '

For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned
as par the need of the program. You can declare a dynamic array using
the ReDim statement.
Syntax for ReDim statement −
ReDim [Preserve] arrayname(subscripts)
Where,
 The Preserve keyword helps to preserve the data in an
existing array, when you resize it.
 arrayname is the name of the array to re-dimension.
 subscripts specifies the new dimension.
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90

ReDim Preserve marks(10)


marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75

For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also
called rectangular arrays.
You can declare a 2-dimensional array of strings as −
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables −
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional
array −
Live Demo

Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '

For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a
jagged array named scores of Integers −
Dim scores As Integer()() = New Integer(5)(){}
The following example illustrates using a jagged array −
Live Demo

Module arrayApl
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer
' output each array element's value

For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
The Array Class
The Array class is the base class for all the arrays in VB.Net. It is defined in
the System namespace. The Array class provides various properties and
methods to work with arrays.

Properties of the Array Class


The following table provides some of the most commonly
used properties of the Array class −

Sr.N Property Name & Description


o

1
IsFixedSize
Gets a value indicating whether the Array has a fixed size.

2
IsReadOnly
Gets a value indicating whether the Array is read-only.

3
Length
Gets a 32-bit integer that represents the total number of elements in
all the dimensions of the Array.

4
LongLength
Gets a 64-bit integer that represents the total number of elements in
all the dimensions of the Array.

5
Rank
Gets the rank (number of dimensions) of the Array.

Methods of the Array Class


The following table provides some of the most commonly
used methods of the Array class −

Sr.N Method Name & Description


o

1
Public Shared Sub Clear (array As Array, index As Integer,
length As Integer)
Sets a range of elements in the Array to zero, to false, or to null,
depending on the element type.

2
Public Shared Sub Copy (sourceArray As Array,
destinationArray As Array, length As Integer)
Copies a range of elements from an Array starting at the first element
and pastes them into another Array starting at the first element. The
length is specified as a 32-bit integer.

3
Public Sub CopyTo (array As Array, index As Integer)
Copies all the elements of the current one-dimensional Array to the
specified one-dimensional Array starting at the specified destination
Array index. The index is specified as a 32-bit integer.

4
Public Function GetLength (dimension As Integer) As Integer
Gets a 32-bit integer that represents the number of elements in the
specified dimension of the Array.

5
Public Function GetLongLength (dimension As Integer) As
Long
Gets a 64-bit integer that represents the number of elements in the
specified dimension of the Array.

6
Public Function GetLowerBound (dimension As Integer) As
Integer
Gets the lower bound of the specified dimension in the Array.

7
Public Function GetType As Type
Gets the Type of the current instance (Inherited from Object).

8
Public Function GetUpperBound (dimension As Integer) As
Integer
Gets the upper bound of the specified dimension in the Array.

9
Public Function GetValue (index As Integer) As Object
Gets the value at the specified position in the one-dimensional Array.
The index is specified as a 32-bit integer.
10
Public Shared Function IndexOf (array As Array,value As
Object) As Integer
Searches for the specified object and returns the index of the first
occurrence within the entire one-dimensional Array.

11
Public Shared Sub Reverse (array As Array)
Reverses the sequence of the elements in the entire one-dimensional
Array.

12
Public Sub SetValue (value As Object, index As Integer)
Sets a value to the element at the specified position in the one-
dimensional Array. The index is specified as a 32-bit integer.

13
Public Shared Sub Sort (array As Array)
Sorts the elements in an entire one-dimensional Array using the
IComparable implementation of each element of the Array.

14
Public Overridable Function ToString As String
Returns a string that represents the current object (Inherited from
Object).

For complete list of Array class properties and methods, please consult
Microsoft documentation.
Example
The following program demonstrates use of some of the methods of the
Array class:
Live Demo

Module arrayApl
Sub Main()
Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
Dim temp As Integer() = list
Dim i As Integer
Console.Write("Original Array: ")

For Each i In list


Console.Write("{0} ", i)
Next i
Console.WriteLine()
' reverse the array
Array.Reverse(temp)
Console.Write("Reversed Array: ")

For Each i In temp


Console.Write("{0} ", i)
Next i
Console.WriteLine()
'sort the array
Array.Sort(list)
Console.Write("Sorted Array: ")

For Each i In list


Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72

Collection classes are specialized classes for data storage and retrieval.
These classes provide support for stacks, queues, lists, and hash tables.
Most collection classes implement the same interfaces.
Collection classes serve various purposes, such as allocating memory
dynamically to elements and accessing a list of items on the basis of an
index, etc. These classes create collections of objects of the Object class,
which is the base class for all data types in VB.Net.

Various Collection Classes and Their Usage


The following are the various commonly used classes of
the System.Collection namespace. Click the following links to check
their details.

Class Description and Useage

ArrayList It represents ordered collection of an object that can


be indexed individually.
It is basically an alternative to an array. However, unlike
array, you can add and remove items from a list at a
specified position using an index and the array resizes itself
automatically. It also allows dynamic memory allocation, add,
search and sort items in the list.

Hashtable It uses a key to access the elements in the collection.


A hash table is used when you need to access elements by
using key, and you can identify a useful key value. Each item
in the hash table has a key/value pair. The key is used to
access the items in the collection.

SortedList It uses a key as well as an index to access the items in a


list.
A sorted list is a combination of an array and a hash table. It
contains a list of items that can be accessed using a key or
an index. If you access items using an index, it is an
ArrayList, and if you access items using a key, it is a
Hashtable. The collection of items is always sorted by the key
value.

Stack It represents a last-in, first out collection of object.


It is used when you need a last-in, first-out access of items.
When you add an item in the list, it is called pushing the
item, and when you remove it, it is called popping the item.

Queue It represents a first-in, first out collection of object.


It is used when you need a first-in, first-out access of items.
When you add an item in the list, it is called enqueue, and
when you remove an item, it is called deque.

BitArray It represents an array of the binary representation using


the values 1 and 0.
It is used when you need to store the bits but do not know
the number of bits in advance. You can access items from
the BitArray collection by using an integer index, which
starts from zero.
VB.Net - Regular Expressions
Previous Page
Next Page
A regular expression is a pattern that could be matched against an
input text. The .Net framework provides a regular expression engine that
allows such matching. A pattern consists of one or more character literals,
operators, or constructs.

Constructs for Defining Regular Expressions


There are various categories of characters, operators, and constructs that
lets you to define regular expressions. Click the following links to find
these constructs.
 Character escapes
 Character classes
 Anchors
 Grouping constructs
 Quantifiers
 Backreference constructs
 Alternation constructs
 Substitutions
 Miscellaneous constructs
The Regex Class
The Regex class is used for representing a regular expression.
The Regex class has the following commonly used methods −

Sr.N Methods & Description


o.

1
Public Function IsMatch (input As String) As Boolean
Indicates whether the regular expression specified in the Regex
constructor finds a match in a specified input string.

2
Public Function IsMatch (input As String, startat As Integer )
As Boolean
Indicates whether the regular expression specified in the Regex
constructor finds a match in the specified input string, beginning at
the specified starting position in the string.

3
Public Shared Function IsMatch (input As String, pattern As
String ) As Boolean
Indicates whether the specified regular expression finds a match in
the specified input string.

4
Public Function Matches (input As String) As MatchCollection
Searches the specified input string for all occurrences of a regular
expression.

5
Public Function Replace (input As String, replacement As
String) As String
In a specified input string, replaces all strings that match a regular
expression pattern with a specified replacement string.

6
Public Function Split (input As String) As String()
Splits an input string into an array of substrings at the positions
defined by a regular expression pattern specified in the Regex
constructor.

For the complete list of methods and properties, please consult Microsoft
documentation.

Example 1
The following example matches words that start with 'S' −
Live Demo

Imports System.Text.RegularExpressions
Module regexProg
Sub showMatch(ByVal text As String, ByVal expr As String)
Console.WriteLine("The Expression: " + expr)
Dim mc As MatchCollection = Regex.Matches(text, expr)
Dim m As Match

For Each m In mc
Console.WriteLine(m)
Next m
End Sub

Sub Main()
Dim str As String = "A Thousand Splendid Suns"
Console.WriteLine("Matching words that start with 'S': ")
showMatch(str, "\bS\S*")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns
Example 2
The following example matches words that start with 'm' and ends with 'e'

Live Demo

Imports System.Text.RegularExpressions
Module regexProg
Sub showMatch(ByVal text As String, ByVal expr As String)
Console.WriteLine("The Expression: " + expr)
Dim mc As MatchCollection = Regex.Matches(text, expr)
Dim m As Match

For Each m In mc
Console.WriteLine(m)
Next m
End Sub

Sub Main()
Dim str As String = "make a maze and manage to measure it"
Console.WriteLine("Matching words that start with 'm' and ends with 'e':
")
showMatch(str, "\bm\S*e\b")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure
Example 3
This example replaces extra white space −
Live Demo

Imports System.Text.RegularExpressions
Module regexProg
Sub Main()
Dim input As String = "Hello World "
Dim pattern As String = "\\s+"
Dim replacement As String = " "
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement)

Console.WriteLine("Original String: {0}", input)


Console.WriteLine("Replacement String: {0}", result)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Original String: Hello World
Replacement String: Hello World
Unit- IV
VB.Net - Sub Procedures
As we mentioned in the previous chapter, Sub procedures are procedures
that do not return any value. We have been using the Sub procedure Main
in all our examples. We have been writing console applications so far in
these tutorials. When these applications start, the control goes to the Main
Sub procedure, and it in turn, runs any other statements constituting the
body of the program.

Defining Sub Procedures


The Sub statement is used to declare the name, parameter and the body
of a sub procedure. The syntax for the Sub statement is −
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
 Modifiers − specify the access level of the procedure;
possible values are - Public, Private, Protected, Friend,
Protected Friend and information regarding overloading,
overriding, sharing, and shadowing.
 SubName − indicates the name of the Sub
 ParameterList − specifies the list of the parameters
Example
The following example demonstrates a Sub procedure CalculatePay that
takes two parameters hours and wages and displays the total pay of an
employee −
Live Demo
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00
Passing Parameters by Value
This is the default mechanism for passing parameters to a method. In this
mechanism, when a method is called, a new storage location is created for
each value parameter. The values of the actual parameters are copied
into them. So, the changes made to the parameter inside the method
have no effect on the argument.
In VB.Net, you declare the reference parameters using
the ByVal keyword. The following example demonstrates the concept −
Live Demo

Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been
changed inside the function.

Passing Parameters by Reference


A reference parameter is a reference to a memory location of a variable.
When you pass parameters by reference, unlike value parameters, a new
storage location is not created for these parameters. The reference
parameters represent the same memory location as the actual parameters
that are supplied to the method.
In VB.Net, you declare the reference parameters using
the ByRef keyword. The following example demonstrates this −
Live Demo

Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

When you define a class, you define a blueprint for a data type. This
doesn't actually define any data, but it does define what the class name
means, that is, what an object of the class will consist of and what
operations can be performed on such an object.
Objects are instances of a class. The methods and variables that
constitute a class are called members of the class.

Class Definition
A class definition starts with the keyword Class followed by the class
name; and the class body, ended by the End Class statement. Following is
the general form of a class definition −
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable
] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
 attributelist is a list of attributes that apply to the class.
Optional.
 accessmodifier defines the access levels of the class, it has
values as - Public, Protected, Friend, Protected Friend and
Private. Optional.
 Shadows indicate that the variable re-declares and hides an
identically named element, or set of overloaded elements, in a
base class. Optional.
 MustInherit specifies that the class can be used only as a
base class and that you cannot create an object directly from
it, i.e., an abstract class. Optional.
 NotInheritable specifies that the class cannot be used as a
base class.
 Partial indicates a partial definition of the class.
 Inherits specifies the base class it is inheriting from.
 Implements specifies the interfaces the class is inheriting
from.
The following example demonstrates a Box class, with three data
members, length, breadth and height −
Live Demo
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here

' box 1 specification


Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0

' box 2 specification


Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0

'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)

'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Volume of Box1 : 210
Volume of Box2 : 1560
Member Functions and Encapsulation
A member function of a class is a function that has its definition or its
prototype within the class definition like any other variable. It operates on
any object of the class of which it is a member and has access to all the
members of a class for that object.
Member variables are attributes of an object (from design perspective)
and they are kept private to implement encapsulation. These variables
can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class
members in a class −
Live Demo
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public Sub setLength(ByVal len As Double)
length = len
End Sub

Public Sub setBreadth(ByVal bre As Double)


breadth = bre
End Sub

Public Sub setHeight(ByVal hei As Double)


height = hei
End Sub

Public Function getVolume() As Double


Return length * breadth * height
End Function
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here

' box 1 specification


Box1.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)

'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)

' volume of box 1


volume = Box1.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)

'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Volume of Box1 : 210
Volume of Box2 : 1560
Constructors and Destructors
A class constructor is a special member Sub of a class that is executed
whenever we create new objects of that class. A constructor has the
name New and it does not have any return type.
Following program explains the concept of constructor −
Live Demo

Class Line
Private length As Double ' Length of a line
Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Object is being created
Length of line : 6
A default constructor does not have any parameter, but if you need, a
constructor can have parameters. Such constructors are
called parameterized constructors. This technique helps you to assign
initial value to an object at the time of its creation as shown in the
following example −
Live Demo

Class Line
Private length As Double ' Length of a line
Public Sub New(ByVal len As Double) 'parameterised constructor
Console.WriteLine("Object is being created, length = {0}", len)
length = len
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub

Public Function getLength() As Double


Return length
End Function
Shared Sub Main()
Dim line As Line = New Line(10.0)
Console.WriteLine("Length of line set by constructor : {0}",
line.getLength())
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line set by setLength : {0}",
line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6
A destructor is a special member Sub of a class that is executed
whenever an object of its class goes out of scope.
A destructor has the name Finalize and it can neither return a value nor
can it take any parameters. Destructor can be very useful for releasing
resources before coming out of the program like closing files, releasing
memories, etc.
Destructors cannot be inherited or overloaded.
Following example explains the concept of destructor −
Live Demo

Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub

Protected Overrides Sub Finalize() ' destructor


Console.WriteLine("Object is being deleted")
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function

Shared Sub Main()


Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Object is being created
Length of line : 6
Object is being deleted

Shared Members of a VB.Net Class


We can define class members as static using the Shared keyword. When
we declare a member of a class as Shared, it means no matter how many
objects of the class are created, there is only one copy of the member.
The keyword Shared implies that only one instance of the member exists
for a class. Shared variables are used for defining constants because their
values can be retrieved by invoking the class without creating an instance
of it.
Shared variables can be initialized outside the member function or class
definition. You can also initialize Shared variables inside the class
definition.
You can also declare a member function as Shared. Such functions can
access only Shared variables. The Shared functions exist even before the
object is created.
The following example demonstrates the use of shared members −
Live Demo

Class StaticVar
Public Shared num As Integer
Public Sub count()
num = num + 1
End Sub
Public Shared Function getNum() As Integer
Return num
End Function
Shared Sub Main()
Dim s As StaticVar = New StaticVar()
s.count()
s.count()
s.count()
Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Value of variable num: 3
Inheritance
One of the most important concepts in object-oriented programming is
that of inheritance. Inheritance allows us to define a class in terms of
another class which makes it easier to create and maintain an application.
This also provides an opportunity to reuse the code functionality and fast
implementation time.
When creating a class, instead of writing completely new data members
and member functions, the programmer can designate that the new class
should inherit the members of an existing class. This existing class is
called the base class, and the new class is referred to as
the derived class.

Base & Derived Classes


A class can be derived from more than one class or interface, which
means that it can inherit data and functions from multiple base classes or
interfaces.
The syntax used in VB.Net for creating derived classes is as follows −
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle −
Live Demo

' Base class


Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Total area: 35
Base Class Initialization
The derived class inherits the base class member variables and member
methods. Therefore, the super class object should be created before the
subclass is created. The super class or the base class is implicitly known
as MyBase in VB.Net
The following program demonstrates this −
Live Demo

' Base class


Class Rectangle
Protected width As Double
Protected length As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
length = l
width = w
End Sub
Public Function GetArea() As Double
Return (width * length)
End Function
Public Overridable Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
'end class Rectangle
End Class
'Derived class
Class Tabletop : Inherits Rectangle
Private cost As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
MyBase.New(l, w)
End Sub
Public Function GetCost() As Double
Dim cost As Double
cost = GetArea() * 70
Return cost
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
'end class Tabletop
End Class
Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following
result −
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

VB.Net - Exception Handling


Previous Page
Next Page
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 ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.

Exception Classes in .Net Framework


In the .Net Framework, exceptions are represented by classes. The
exception classes in .Net Framework are mainly directly or indirectly
derived from the System.Exception class. Some of the exception classes
derived from the System.Exception class are
the System.ApplicationException and System.SystemException clas
ses.
The System.ApplicationException class supports exceptions generated
by application programs. So the exceptions defined by the programmers
should derive from this class.
The System.SystemException class is the base class for all predefined
system exception.
The following table provides some of the predefined exception classes
derived from the Sytem.SystemException class −

Exception Class Description

System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeExcepti Handles errors generated when a method


on refers to an array index out of range.

System.ArrayTypeMismatchExcep Handles errors generated when type is


tion mismatched with the array type.

System.NullReferenceException Handles errors generated from deferencing a


null object.

System.DivideByZeroException Handles errors generated from dividing a


dividend with zero.

System.InvalidCastException Handles errors generated during


typecasting.

System.OutOfMemoryException Handles errors generated from insufficient


free memory.

System.StackOverflowException Handles errors generated from stack


overflow.

Handling Exceptions
VB.Net provides a structured solution to the exception handling problems
in the form of try and catch blocks. Using these blocks the core program
statements are separated from the error-handling statements.
These error handling blocks are implemented using
the Try, Catch and Finally keywords. Following is an example of throwing
an exception when dividing by zero condition occurs −
Live Demo

Module exceptionProg
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
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
Exception caught: System.DivideByZeroException: Attempted to divide by
zero.
at ...
Result: 0

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes
are derived from the ApplicationException class. The following example
demonstrates this −
Live Demo

Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.
You can use a throw statement in the catch block to throw the present
object as −
Throw [ expression ]
The following program demonstrates this −
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _ is being thrown
here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
A custom exception is being thrown here...
Now inside the Finally Block

VB.Net - File Handling


A file is a collection of data stored in a disk with a specific name and a
directory path. When a file is opened for reading or writing, it becomes
a stream.
The stream is basically the sequence of bytes passing through the
communication path. There are two main streams: the input stream and
the output stream. The input stream is used for reading data from file
(read operation) and the output stream is used for writing into the file
(write operation).

VB.Net I/O Classes


The System.IO namespace has various classes that are used for
performing various operations with files, like creating and deleting files,
reading from or writing to a file, closing a file, etc.
The following table shows some commonly used non-abstract classes in
the System.IO namespace −

I/O Class Description

BinaryReader Reads primitive data from a binary stream.

BinaryWriter Writes primitive data in binary format.

BufferedStream A temporary storage for a stream of bytes.

Directory Helps in manipulating a directory structure.

DirectoryInfo Used for performing operations on directories.

DriveInfo Provides information for the drives.

File Helps in manipulating files.

FileInfo Used for performing operations on files.

FileStream Used to read from and write to any location in a file.

MemoryStream Used for random access of streamed data stored in


memory.

Path Performs operations on path information.

StreamReader Used for reading characters from a byte stream.

StreamWriter Is used for writing characters to a stream.

StringReader Is used for reading from a string buffer.


StringWriter Is used for writing into a string buffer.

The FileStream Class


The FileStream class in the System.IO namespace helps in reading from,
writing to and closing files. This class derives from the abstract class
Stream.
You need to create a FileStream object to create a new file or open an
existing file. The syntax for creating a FileStream object is as follows −
Dim <object_name> As FileStream = New FileStream(<file_name>,
<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare
Enumerator>)
For example, for creating a FileStream object F for reading a file
named sample.txt −
Dim f1 As FileStream = New FileStream("sample.txt",
FileMode.OpenOrCreate, FileAccess.ReadWrite)
Parameter Description

FileMode
The FileMode enumerator defines various methods for
opening files. The members of the FileMode enumerator are

 Append − It opens an existing file and puts
cursor at the end of file, or creates the file, if the
file does not exist.
 Create − It creates a new file.
 CreateNew − It specifies to the operating
system that it should create a new file.
 Open − It opens an existing file.
 OpenOrCreate − It specifies to the operating
system that it should open a file if it exists,
otherwise it should create a new file.
 Truncate − It opens an existing file and
truncates its size to zero bytes.

FileAccess
FileAccess enumerators have
members: Read, ReadWrite and Write.

FileShare
FileShare enumerators have the following members −
 Inheritable − It allows a file handle to pass
inheritance to the child processes
 None − It declines sharing of the current file
 Read − It allows opening the file for reading
 ReadWrite − It allows opening the file for
reading and writing
 Write − It allows opening the file for writing

Example
The following program demonstrates use of the FileStream class −
Live Demo

Imports System.IO
Module fileProg
Sub Main()
Dim f1 As FileStream = New FileStream("sample.txt", _
FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim i As Integer

For i = 0 To 20
f1.WriteByte(CByte(i))
Next i
f1.Position = 0

For i = 0 To 20
Console.Write("{0} ", f1.ReadByte())
Next i
f1.Close()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
Advanced File Operations in VB.Net
The preceding example provides simple file operations in VB.Net.
However, to utilize the immense powers of System.IO classes, you need to
know the commonly used properties and methods of these classes.
We will discuss these classes and the operations they perform in the
following sections. Please click the links provided to get to the individual
sections −

Sr.N Topic and Description


o.

1
Reading from and Writing into Text files
It involves reading from and writing into text files.
The StreamReader and StreamWriter classes help to accomplish
it.
2
Reading from and Writing into Binary files
It involves reading from and writing into binary files.
The BinaryReader and BinaryWriter classes help to accomplish
this.

3
Manipulating the Windows file system
It gives a VB.Net programmer the ability to browse and locate
Windows files and directories.

There are many built-in dialog boxes to be used in Windows forms for
various tasks like opening and saving files, printing a page, providing
choices for colors, fonts, page setup, etc., to the user of an application.
These built-in dialog boxes reduce the developer's time and workload.
All of these dialog box control classes inherit from
the CommonDialog class and override the RunDialog() function of the
base class to create the specific dialog box.
The RunDialog() function is automatically invoked when a user of a dialog
box calls its ShowDialog() function.
The ShowDialog method is used to display all the dialog box controls at
run-time. It returns a value of the type of DialogResult enumeration. The
values of DialogResult enumeration are −
 Abort − returns DialogResult.Abort value, when user clicks an
Abort button.
 Cancel − returns DialogResult.Cancel, when user clicks a
Cancel button.
 Ignore − returns DialogResult.Ignore, when user clicks an
Ignore button.
 No − returns DialogResult.No, when user clicks a No button.
 None − returns nothing and the dialog box continues running.
 OK − returns DialogResult.OK, when user clicks an OK button
 Retry − returns DialogResult.Retry , when user clicks an Retry
button
 Yes − returns DialogResult.Yes, when user clicks an Yes
button
The following diagram shows the common dialog class inheritance −
All these above-mentioned classes have corresponding controls that could
be added from the Toolbox during design time. You can include relevant
functionality of these classes to your application, either by instantiating
the class programmatically or by using relevant controls.
When you double click any of the dialog controls in the toolbox or drag the
control onto the form, it appears in the Component tray at the bottom of
the Windows Forms Designer, they do not directly show up on the form.
The following table lists the commonly used dialog box controls. Click the
following links to check their detail −

Sr.N Control & Description


o.

1
ColorDialog
It represents a common dialog box that displays available colors
along with controls that enable the user to define custom colors.

2
FontDialog
It prompts the user to choose a font from among those installed on
the local computer and lets the user select the font, font size, and
color.

3
OpenFileDialog
It prompts the user to open a file and allows the user to select a file
to open.

4
SaveFileDialog
It prompts the user to select a location for saving a file and allows the
user to specify the name of the file to save data.

5
PrintDialog
It lets the user to print documents by selecting a printer and choosing
which sections of the document to print from a Windows Forms
application.

In this chapter, let us study the following concepts −


 Adding menus and sub menus in an application
 Adding the cut, copy and paste functionalities in a form
 Anchoring and docking controls in a form
 Modal forms
Adding Menus and Sub Menus in an
Application
Traditionally, the Menu, MainMenu, ContextMenu, and MenuItem classes
were used for adding menus, sub-menus and context menus in a Windows
application.
Now, the MenuStrip,
the ToolStripMenuItem, ToolStripDropDown and ToolStripDropDow
nMenu controls replace and add functionality to the Menu-related
controls of previous versions. However, the old control classes are
retained for both backward compatibility and future use.
Let us create a typical windows main menu bar and sub menus using the
old version controls first since these controls are still much used in old
applications.
Following is an example, which shows how we create a menu bar with
menu items: File, Edit, View and Project. The File menu has the sub menus
New, Open and Save.
Let's double click on the Form and put the following code in the opened
window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
'defining the main menu bar
Dim mnuBar As New MainMenu()
'defining the menu items for the main menu bar
Dim myMenuItemFile As New MenuItem("&File")
Dim myMenuItemEdit As New MenuItem("&Edit")
Dim myMenuItemView As New MenuItem("&View")
Dim myMenuItemProject As New MenuItem("&Project")

'adding the menu items to the main menu bar


mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)

' defining some sub menus


Dim myMenuItemNew As New MenuItem("&New")
Dim myMenuItemOpen As New MenuItem("&Open")
Dim myMenuItemSave As New MenuItem("&Save")

'add sub menus to the File menu


myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)

'add the main menu to the form


Me.Menu = mnuBar

' Set the caption bar text of the form.


Me.Text = "tutorialspoint.com"
End Sub
End Class
When the above code is executed and run using Start button available at
the Microsoft Visual Studio tool bar, it will show the following window −

Windows Forms contain a rich set of classes for creating your own custom
menus with modern appearance, look and feel.
The MenuStrip, ToolStripMenuItem, ContextMenuStrip controls are
used to create menu bars and context menus efficiently.
Click the following links to check their details −
Sr.N Control & Description
o.

1
MenuStrip
It provides a menu system for a form.

2
ToolStripMenuItem
It represents a selectable option displayed on
a MenuStrip or ContextMenuStrip. The ToolStripMenuItem control
replaces and adds functionality to the MenuItem control of previous
versions.

3
ContextMenuStrip
It represents a shortcut menu.

Adding the Cut, Copy and Paste


Functionalities in a Form
The methods exposed by the ClipBoard class are used for adding the cut,
copy and paste functionalities in an application. The ClipBoard class
provides methods to place data on and retrieve data from the system
Clipboard.
It has the following commonly used methods −

Sr.N Method Name & Description


o.

1
Clear
Removes all data from the Clipboard.

2
ContainsData
Indicates whether there is data on the Clipboard that is in the
specified format or can be converted to that format.

3
ContainsImage
Indicates whether there is data on the Clipboard that is in the Bitmap
format or can be converted to that format.
4
ContainsText
Indicates whether there is data on the Clipboard in the Text or
UnicodeText format, depending on the operating system.

5
GetData
Retrieves data from the Clipboard in the specified format.

6
GetDataObject
Retrieves the data that is currently on the system Clipboard.

7
GetImage
Retrieves an image from the Clipboard.

8
GetText
Retrieves text data from the Clipboard in the Text or UnicodeText
format, depending on the operating system.

9
GetText(TextDataFormat)
Retrieves text data from the Clipboard in the format indicated by the
specified TextDataFormat value.

10
SetData
Clears the Clipboard and then adds data in the specified format.

11
SetText(String)
Clears the Clipboard and then adds text data in the Text or
UnicodeText format, depending on the operating system.

Following is an example, which shows how we cut, copy and paste data
using methods of the Clipboard class. Take the following steps −
 Add a rich text box control and three button controls on the
form.
 Change the text property of the buttons to Cut, Copy and
Paste, respectively.
 Double click on the buttons to add the following code in the
code editor −
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
Clipboard.SetDataObject(RichTextBox1.SelectedText)
RichTextBox1.SelectedText = ""
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) _


Handles Button2.Click
Clipboard.SetDataObject(RichTextBox1.SelectedText)
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) _


Handles Button3.Click
Dim iData As IDataObject
iData = Clipboard.GetDataObject()
If (iData.GetDataPresent(DataFormats.Text)) Then
RichTextBox1.SelectedText = iData.GetData(DataFormats.Text)
Else
RichTextBox1.SelectedText = " "
End If
End Sub
End Class
When the above code is executed and run using Start button available at
the Microsoft Visual Studio tool bar, it will show the following window −

Enter some text and check how the buttons work.

Anchoring and Docking Controls in a Form


Anchoring allows you to set an anchor position for a control to the edges
of its container control, for example, the form. The Anchor property of the
Control class allows you to set values of this property. The Anchor
property gets or sets the edges of the container to which a control is
bound and determines how a control is resized with its parent.
When you anchor a control to a form, the control maintains its distance
from the edges of the form and its anchored position, when the form is
resized.
You can set the Anchor property values of a control from the Properties
window −

For example, let us add a Button control on a form and set its anchor
property to Bottom, Right. Run this form to see the original position of the
Button control with respect to the form.

Now, when you stretch the form, the distance between the Button and the
bottom right corner of the form remains same.
Docking of a control means docking it to one of the edges of its
container. In docking, the control fills certain area of the container
completely.
The Dock property of the Control class does this. The Dock property gets
or sets which control borders are docked to its parent control and
determines how a control is resized with its parent.
You can set the Dock property values of a control from the Properties
window −

For example, let us add a Button control on a form and set its Dock
property to Bottom. Run this form to see the original position of the Button
control with respect to the form.
Now, when you stretch the form, the Button resizes itself with the form.

Modal Forms
Modal Forms are those forms that need to be closed or hidden before
you can continue working with the rest of the application. All dialog boxes
are modal forms. A MessageBox is also a modal form.
You can call a modal form by two ways −
 Calling the ShowDialog method
 Calling the Show method
Let us take up an example in which we will create a modal form, a dialog
box. Take the following steps −
 Add a form, Form1 to your application, and add two labels and
a button control to Form1
 Change the text properties of the first label and the button to
'Welcome to Tutorials Point' and 'Enter your Name',
respectively. Keep the text properties of the second label as
blank.
 Add a new Windows Form, Form2, and add two buttons, one
label, and a text box to Form2.
 Change the text properties of the buttons to OK and Cancel,
respectively. Change the text properties of the label to 'Enter
your name:'.
 Set the FormBorderStyle property of Form2 to FixedDialog, for
giving it a dialog box border.
 Set the ControlBox property of Form2 to False.
 Set the ShowInTaskbar property of Form2 to False.
 Set the DialogResult property of the OK button to OK and the
Cancel button to Cancel.

Add the following code snippets in the Form2_Load method of Form2 −


Private Sub Form2_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
AcceptButton = Button1
CancelButton = Button2
End Sub
Add the following code snippets in the Button1_Click method of Form1 −
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Dim frmSecond As Form2 = New Form2()

If frmSecond.ShowDialog() = DialogResult.OK Then


Label2.Text = frmSecond.TextBox1.Text
End If
End Sub
When the above code is executed and run using Start button available at
the Microsoft Visual Studio tool bar, it will show the following window −

Clicking on the 'Enter your Name' button displays the second form −

Clicking on the OK button takes the control and information back from the
modal form to the previous form −
VB.Net - Event Handling
Events are basically a user action like key press, clicks, mouse
movements, etc., or some occurrence like system generated notifications.
Applications need to respond to events when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a
menu item, all are examples of events. An event is an action that calls a
function or may cause another event. Event handlers are functions that
tell how to respond to an event.
VB.Net is an event-driven language. There are mainly two types of events

 Mouse events
 Keyboard events
Handling Mouse Events
Mouse events occur with mouse movements in forms and controls.
Following are the various mouse events related with a Control class −
 MouseDown − it occurs when a mouse button is pressed
 MouseEnter − it occurs when the mouse pointer enters the
control
 MouseHover − it occurs when the mouse pointer hovers over
the control
 MouseLeave − it occurs when the mouse pointer leaves the
control
 MouseMove − it occurs when the mouse pointer moves over
the control
 MouseUp − it occurs when the mouse pointer is over the
control and the mouse button is released
 MouseWheel − it occurs when the mouse wheel moves and
the control has focus
The event handlers of the mouse events get an argument of
type MouseEventArgs. The MouseEventArgs object is used for handling
mouse events. It has the following properties −
 Buttons − indicates the mouse button pressed
 Clicks − indicates the number of clicks
 Delta − indicates the number of detents the mouse wheel
rotated
 X − indicates the x-coordinate of mouse click
 Y − indicates the y-coordinate of mouse click
Example
Following is an example, which shows how to handle mouse events. Take
the following steps −
 Add three labels, three text boxes and a button control in the
form.
 Change the text properties of the labels to - Customer ID,
Name and Address, respectively.
 Change the name properties of the text boxes to txtID,
txtName and txtAddress, respectively.
 Change the text property of the button to 'Submit'.
 Add the following code in the code editor window −
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub

Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_


Handles txtID.MouseEnter
'code for handling mouse enter on ID textbox
txtID.BackColor = Color.CornflowerBlue
txtID.ForeColor = Color.White
End Sub

Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _


Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox
txtID.BackColor = Color.White
txtID.ForeColor = Color.Blue
End Sub

Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _


Handles txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub

Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _


Handles txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White
txtName.ForeColor = Color.Blue
End Sub

Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _


Handles txtAddress.MouseEnter
'code for handling mouse enter on Address textbox
txtAddress.BackColor = Color.CornflowerBlue
txtAddress.ForeColor = Color.White
End Sub

Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _


Handles txtAddress.MouseLeave
'code for handling mouse leave on Address textbox
txtAddress.BackColor = Color.White
txtAddress.ForeColor = Color.Blue
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
MsgBox("Thank you " & txtName.Text & ", for your kind cooperation")
End Sub
End Class
When the above code is executed and run using Start button available at
the Microsoft Visual Studio tool bar, it will show the following window −

Try to enter text in the text boxes and check the mouse events −
Handling Keyboard Events
Following are the various keyboard events related with a Control class −
 KeyDown − occurs when a key is pressed down and the
control has focus
 KeyPress − occurs when a key is pressed and the control has
focus
 KeyUp − occurs when a key is released while the control has
focus
The event handlers of the KeyDown and KeyUp events get an argument of
type KeyEventArgs. This object has the following properties −
 Alt − it indicates whether the ALT key is pressed
 Control − it indicates whether the CTRL key is pressed
 Handled − it indicates whether the event is handled
 KeyCode − stores the keyboard code for the event
 KeyData − stores the keyboard data for the event
 KeyValue − stores the keyboard value for the event
 Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or
Alt) are pressed
 Shift − it indicates if the Shift key is pressed
The event handlers of the KeyDown and KeyUp events get an argument of
type KeyEventArgs. This object has the following properties −
 Handled − indicates if the KeyPress event is handled
 KeyChar − stores the character corresponding to the key
pressed
Example
Let us continue with the previous example to show how to handle
keyboard events. The code will verify that the user enters some numbers
for his customer ID and age.
 Add a label with text Property as 'Age' and add a
corresponding text box named txtAge.
 Add the following codes for handling the KeyUP events of the
text box txtID.
Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtID.KeyUp

If (Not Char.IsNumber(ChrW(e.KeyCode))) Then


MessageBox.Show("Enter numbers for your Customer ID")
txtID.Text = " "
End If
End Sub
 Add the following codes for handling the KeyUP events of the
text box txtID.
Private Sub txtAge_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtAge.KeyUp

If (Not Char.IsNumber(ChrW(e.keyCode))) Then


MessageBox.Show("Enter numbers for age")
txtAge.Text = " "
End If
End Sub
When the above code is executed and run using Start button available at
the Microsoft Visual Studio tool bar, it will show the following window −

If you leave the text for age or ID as blank or enter some non-numeric
data, it gives a warning message box and clears the respective text −
Adding multiple forms in VB, Hiding & showing forms, Load & unload statements, creating
menu, submenu, popup menus, Activate & deactivate events, Form-load event, menu
designing in VB Simple programs in VB.

VB.NET Menu Control


A menu is used as a menu bar in the Windows form that contains a list of
related commands, and it is implemented through MenuStrip Control. The
Menu control is also known as the VB.NET MenuStrip Control. The menu
items are created with ToolStripMenuItem Objects. Furthermore,
the ToolStripDropDownMenu and ToolStripMenuItem objects enable
full control over the structure, appearance, functionalities to create menu
items, submenus, and drop-down menus in a VB.NET application.

Let's create a MenuBar by dragging a MenuStrip control from the toolbox


and dropping it to the Windows form.

Step 1. Drag the MenuStrip control from the toolbox and drop it on to the
Form.
Step 2: Once the MenuStrip is added to the form, we can set various
properties of the Menu by clicking on the MenuStrip control.

Backward Skip 10sPlay VideoForward Skip 10s

Properties of the MenuStrip Control


There are following properties of the VB.NET MenuStrip control.

Properties Description

CanOverflow The CanOverflow property is used to authenticate whether the co


supports overflow functionality by setting values in the MenuStrip control.

Stretch The Stretch property is used to obtain a value that specifies whether
menustrip stretches from end to end in the MenuStrip control.

GripStyle The GripStyle property obtains or sets the visibility of the grip that uses
reposition of the menu strip control.

ShowItemToolT It is used to obtain or set the value that determines if the ToolTips
ips displayed for the MenuStrip Control.

DefaultSize The DefaultSize property is used to get the default horizontal and ver
dimension of the MenuStrip in pixel when it is first created.

Methods of the MenuStrip Control


Method Description
CreateAccessibilityInst It is used to create a new accessibility instance for the MenuS
ance() Control.

ProcessCmdKey() The ProcessCmdKey method is used to process the command ke


the MenuStrip Control.

CreateDefaultItem() The CreateDefaultItem method is used to create


ToolStripMenuItem with the specified text, image, and e
handlers for the new MenuStrip.

OnMenuActivate() It is used to initiate the MenuActivate event in the MenuStrip con

OnMenuDeactivate() It is used to start the MenuDeactivate event in the MenuS


control.

Events of the MenuStrip Control


Events Description

MenuActivat When a user uses a menu bar control with a mouse or keyboard, a MenuActi
e event occurs.

MenuDeactiv The MenuDeactivate event occurs when the MenuStrip control is deactivate
ate the Windows form.

Let's create a program to display the menu bar in the Windows form.

In this image, we have created the menu and sub-items of the menu bar in
the form.
Now, we write the Shortcut keys for the File subitems, such as New ->
Ctrl + N, Open -> Ctrl + O, etc.

After that, we can see the subitems of the Files with their Shortcut keys,
as shown below.
Menus.vb

1. Public Class Menus


2. Private Sub Menus_Load(sender As Object, e As EventArgs) Handles MyB
ase.Load
3. Me.Text = "javatpoint.com" 'set the title of the bar
4. BackColor = Color.SkyBlue
5. End Sub
6.
7. Private Sub ExitToolStripMenuItem_Click(sender As Object, e As E
ventArgs) Handles ExitToolStripMenuItem.Click
8. Me.Dispose() ' exit from the form
9. End Sub
10.End Class

Output:
Click on the File menu that shows the multiple options related to files.

VB.NET MDI Form


MDI stands for Multiple Document Interface applications that allow
users to work with multiple documents by opening more than one
document at a time. Whereas, a Single Document Interface
(SDI) application can manipulate only one document at a time.

The MDI applications act as the parent and child relationship in a form. A
parent form is a container that contains child forms, while child forms can
be multiple to display different modules in a parent form.

VB.NET has folowing rules for creating a form as an MDI form.


1. MidParent: The MidParent property is used to set a parent form to a child
form.
2. ActiveMdiChild: The ActiveMdiChild property is used to get the reference
of the current child form.
3. IsMdiContainer: The IsMdiContainer property set a Boolean value to True
that represents the creation of a form as an MDI form.
4. LayoutMdi(): The LayoutMdi() method is used to arrange the child forms
in the parent or main form.
5. Controls: It is used to get the reference of control from the child form.

Let's create a program to display the multiple windows in


the VB.NET Windows Forms.

Backward Skip 10sPlay VideoForward Skip 10s

Step 1: First, we have to open the Windows form and create the Menu bar
with the use of MenuStrip control, as shown below.

Step 2: After creating the Menu, add the Subitems into the Menu bar, as
shown below.
In the above image, we have defined two Subitems, First is the Feedback
Form, and the Second is VB.NET.

Step 3: In the third step, we will create two Forms: The Child Form of
the Main Form or Parent Form.

Here, we have created the first Child Form with the name Form2.

Form2.vb

1. Public Class Form2


2. Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyB
ase.Load
3. Me.Text = "Feedback form" ' Set the title of the form
4. Label1.Text = " Fill the Feedback form"
5. Button1.Text = "Submit"
6. Button1.BackColor = Color.SkyBlue
7. Button2.Text = "Cancel"
8. Button2.BackColor = Color.Red
9. End Sub
10. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Bu
tton1.Click
11. MsgBox(" Successfully submit the feedback form")
12. End Sub
13. Private Sub Button2_Click(sender As Object, e As EventArgs)
Handles Button2.Click
14. Me.Dispose() ' end the form2
15. End Sub
16.End Class

Another Child Form with the name Form3.

Form3.vb

1. Public Class Form3


2. Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyB
ase.Load
3. Label1.Text = "Welcome to JavaTpoint Tutorial Site"
4. Label.BackColor = Color.Green
5. Label2.Text = "This is the VB.NET Tutorial and we are learning t
he VB.NET MDI Form"
6. Label2.BackColor = Color.SkyBlue
7. End Sub
8. End Class

Step 4: Now we write the programming code for the Main or Parent Form,
and here is the code for our Main Form.

MDI_form.vb

1. Public Class MDI_Form


2. Private Sub MDI_Form_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
3. IsMdiContainer = True 'Set the Boolean value to true to create
the form as an MDI form.
4. Me.Text = "javatpoint.com" 'set the title of the form
5. PictureBox1.Image = Image.FromFile("C:\Users\AMIT YADAV\
Desktop\jtp2.png")
6. PictureBox1.Height = 550
7. PictureBox1.Width = 750
8. End Sub
9. Private Sub FeedbackFormToolStripMenuItem_Click(sender As Obj
ect, e As EventArgs) Handles FeedbackFormToolStripMenuItem.Click

10. PictureBox1.Visible = False


11. Dim fm2 As New Form2
12. fm2.MdiParent = Me 'define the parent of form3, where Me represents
the same form
13. fm2.Show() 'Display the form3
14. End Sub
15. Private Sub VBNETToolStripMenuItem_Click(sender As Objec
t, e As EventArgs) Handles VBNETToolStripMenuItem.Click
16. PictureBox1.Visible = False
17. Dim fm3 As New Form3
18. fm3.MdiParent = Me 'define the parent of form3, where Me represent
the same form
19. fm3.Show() 'Display the form3
20. End Sub
21. End Class

Output:

After that, click on the Menu button, it shows two sub-items of the Menu
as Feedback Form and VB.NET. We have clicked on the Feedback Form
that displays the following form on the window.
VB.NET Dialog Box
A Dialog box is a temporary Window for an application that accepts user
response through mouse or keyboard to open a file, save a file,
notifications, alert messages, color, print, openfile dialog box, etc. It is also
useful to create communication and interaction between the user and the
application. Furthermore, the dialog box appears in a form when the
program needs to interact with users, such as when an error occurs, an
alert message, acknowledgment from the user or when the program
requires immediate action or whether the decision is to be saved based on
the changes.

All VB.NET Dialog box inherits the CommonDialog class and overrides
the RunDialog() method of the base class to create the OpenFileDialog
box, PrintDialogbox, Color, and Font Dialog box. The RunDialog() method
is automatically called in a Windows form when the dialog box calls
its ShowDialog() method.

There are following functions of the ShowDialog() method that can be


called at run time in the Windows Form.
o Abort: The Abort Dialog box is used when a user clicks on the Abort
button to return the DialogResult.Abort value.
o Ignore: The Ignore Dialog box is used when a user clicks on the Ignore
button to return the DialogResult.Ignore.
o None: It is used to return nothing when the user clicks on the None
button, and the dialog box is continued running.
o OK: When the user clicks the OK button of the Dialog box, it returns a
DialogResult.OK,
o Cancel: When a user clicks on the Cancel button of the Dialog Box, it
returns DialogResult.Cancel,
o Yes: When a user clicks the Yes button of the dialog box, it returns
DialogResult.Yes.
o Retry: When a user clicks on the Dialog Box Retry button, it returns a
DialogResult.Retry,
o No: When a user clicks on the No button of the Dialog box, it returns
DialogResult.No,

There are the commonly used dialog box controls in the VB.NET Windows
Form.

1. Color Dialog Box: It is used to display the color dialog box that allows the
user to select a color from the predefined colors or specify the custom
colors.
2. Font DialogBox: It is used to create a Font dialog box that allows the user
to select the font, font size, color, and style to be applied to the current
text selection.
3. OpenFile Dialog Box: It is used to create a prompt box that allows the
users to select a file to open and allows the selection of multiple files.
4. Print Dialog Box: It is used to create a print dialog box that allows the
user to print documents by selecting the printer and setting of the page
printed through the Windows application.

Let's create a simple program to display the dialog box in the VB.NET
Windows Forms.

Dialog.vb

1. Public Class Dialog


2. Private Sub Dialog_Load(sender As Object, e As EventArgs) Handles MyB
ase.Load
3. Button1.Text = "Click Me" 'Set the name of button
4. Me.Text = "javatpoint.com" ' Set the title name for the Windows Form

5. Button1.BackColor = Color.Green ' Background color of the butt


on
6. End Sub
7.
8. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Bu
tton1.Click
9. Dim result1 As DialogResult = MessageBox.Show("Is VB.NET pr
ogramming language easy to learn?",
10. "Important Question",
11. MessageBoxButtons.YesNo)
12. End Sub
13. End Class

Output:
Now, click on the Click Me button of the Windows Form, it displays the
dialog box, as shown below.

VB.NET Color Dialog Box


The Color Dialog box is used to display the Color dialog box and the
selection of colors on the Microsoft Windows Application. It allows users to
set or change the color of an object, such as the background color of a
control or the color used to paint an object. Furthermore, the control
dialog box also allows the facility to the user to create a new color by
mixing all other colors of the Color Dialog Box.

Let's create a Color Dialog in the VB.NET Windows form by using the
following steps.

Step 1: Drag the Color Dialog from the toolbox and drop it to
the Windows form, as shown below.
Step 2: Once the Color Dialog is added to the form, we can set various
properties of the Color by clicking on the Color Dialog.

Backward Skip 10sPlay VideoForward Skip 10s

Properties of Color DialogBox


There are following properties of the Color Dialog Box in the Windows
Form.

Properties Description

AllowFullOp The AllowFullOpen property enables the user to set custom colors in Wind
en Forms by setting values in the color dialog box.

Color The Color property is used to set or get the user's selected color from the C
Dialog box.

FullOpen The FullOpen property is used to set a value representing whether the cus
colors will be displayed when the dialog box is opened.

AnyColor The AnyColor property takes a value that is used to display all available colo
the Color dialog box with a set of basic colors.

ShowHelp ShowHelp property enables the user to display the help button in the Color Di
box by setting a value in the dialog box.

CustomColo It is used to set the custom colors that are displayed on the dialog box.
rs

SolidColorO The SolidColorOnly property is used to set a value representing whether


nly dialog box restricts the user from selecting only solid colors.

Events of Color DialogBox


Events Description

Disposed When control or component is terminated by calling the Dispose method, a Disp
event occurs.

HelpRequ When a user clicks the help button of the Color dialog box, the HelpRequest e
est is called.
Methods of Color DialogBox
Method Description

ShowDialog() The ShowDialog () method is used to run a common dialog box with the de
setting.

Dispose() The Dispose() method is used to free all resources used by the Contro
component in the Color Dialog Box.

Equals() The Equals() method is used to check whether the current or defined obje
the same.

OnHelpReque It is used to call the HelpRequest event in the dialog box.


st()

Reset() The Reset() method is used to reset all changes to their default values.
example, the last selected color to be black, and the custom color to be t
default values.

RunDialog() It is used to override a derived class to create a common dialog box.

Let's create a simple program to display the Color dialog box in the
VB.NET Windows Forms.

ColorDialog.vb

1. Public Class ColorDialog


2. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Bu
tton1.Click
3. ColorDialog1.FullOpen = True
4. If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel T
hen
5. RichTextBox1.ForeColor = ColorDialog1.Color
6. RichTextBox1.BackColor = ColorDialog1.Color
7. End If
8. End Sub
9. Private Sub ColorDialog_Load(sender As Object, e As EventArgs) H
andles MyBase.Load
10. Me.Text = "javatpoint.com" 'set the title for the Windows form
11. Button1.Text = "Change TextBox Color"
12. Button2.Text = "Change Form Color"
13. Button3.Text = "Change Label Color"
14. End Sub
15. Private Sub Button2_Click(sender As Object, e As EventArgs)
Handles Button2.Click
16. ColorDialog1.FullOpen = False
17. If ColorDialog1.ShowDialog <> Windows.Forms.DialogRes
ult.Cancel Then
18. Me.BackColor = ColorDialog1.Color 'Change Background color of th
e form
19. End If
20. End Sub
21. Private Sub Button3_Click(sender As Object, e As EventArgs)
Handles Button3.Click
22. ColorDialog1.FullOpen = True
23. If ColorDialog1.ShowDialog <> Windows.Forms.DialogRes
ult.Cancel Then
24. Label1.ForeColor = ColorDialog1.Color 'set the color of the Label
25. End If
26. End Sub
27. End Class

Output:
When we click on the any of the three buttons, it opens the Color popup
window, as shown below.

Click the OK button to display the colored Windows Form, as shown below.
VB.NET Font Dialog Box
The Font Dialog Box allows the user to select the font family, style, and
size for the text in an application. However, a user can also select the font
color and apply the current setting to the selected text of the control by
clicking the Apply button.

Let's create a Font Dialog box in the VB.NET Windows form using the
following steps.

Step 1. We need to drag the Font Dialog box from the toolbox and drop it
to the Windows form, as shown below.
Step2: Once the Font Dialog is added to the form, we can set various
properties of the Font by clicking on the Font Dialog box.

Properties of Font Dialog


There are following properties of the Font Dialog Box in the VB.NET.

Properties Description

ShowApply The ShowApply property sets a value representing whether you wan
display the Apply button on the dialog box.

ShowEffects The ShowEffects property is used to set various effects on the text suc
strikethrough, text color, and underline options by setting values on
FontDialog box.

Font The Font property is used to get or set the selected font to display change

Container The Container property is used to get the IContainer that contains
Component of the Font Dialog Box.

AllowVerticalFo The AllowverticalFonts property is used to set or get a value that repres
nts whether the Font dialog box displays the horizontal and vertical font
displays only horizontals fonts.

AllowScriptCha The AllowScriptChange property is used to set a value that allows the use
nge change the character specified in the Script combo box to show a chara
set other than the currently displayed character.

ScriptOnly The ScriptOnly property is used to set a value that allows the user to se
only the font, the character set of the symbol, and the ANSI character f
the dialog box.

ShowHelp The ShowHelp property is used to set a value representing whether the
button should be displayed in the dialog box.

MaxSize The MaxSize property gets or sets a value that allows the user to select
the maximum point size character.

Options It is used to initialize FontDialog by obtaining values.

Methods of Font Dialog


Method Description

Equals() The Equals() method is used to check whether the current or defined obje
the same.

OnHelpReque It is used to call the HelpRequest event in the dialog box.


st()

Reset() The Reset() method is used to reset all changes to their default values.

Dispose() The Dispose() method is used to free all resources used by the Control or
component in the Dialog Box.

RunDialog() It is used to override a derived class to create a common dialog box.

ShowDialog() The ShowDialog () method is used to run a common dialog box with the de
setting.

CreateObjRef( The CreateObjRef () method is used to create an object that contains all rel
) information to initialize a proxy that can communicate with a remote object

Events of Font Dialog


Events Description
Disposed When control or component is terminated by calling the Dispose() metho
Dispose event occurs.

HelpRequ When a user clicks the Help button of the dialog box, the HelpRequest even
est called.

Apply When a user clicks on the Apply button of the Font dialog box, an apply e
occurs.

Let's create a simple program to display the Font dialog box in the VB.NET
Windows Forms.

FontDialog.vb

1. Public Class FontDialog


2. Private Sub FontDialog_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
3. Me.Text = "javaTpoint.com" 'set the title name for the Window
s form.
4. Button1.Text = "Change Font" 'Set the name of button1
5. Button2.Text = "Exit" 'name of button2
6. Label1.Text = "Uses of Font"
7. End Sub
8. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Bu
tton1.Click
9. FontDialog1.ShowColor = True
10. If FontDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
11. TextBox1.Font = FontDialog1.Font 'Change the font of
the selected string
12. TextBox1.ForeColor = FontDialog1.Color 'Change the color of select
ed string
13. End If
14. End Sub
15. Private Sub Button2_Click(sender As Object, e As EventArgs)
Handles Button2.Click
16. Me.Dispose() 'Terminate the program
17. End Sub
18.End Class
Output:

Write some text in TextArea, as shown below.

Select the string and click the 'Change Font' button; it opens the Font
window. In the Font window, we can change the size, font, and font style
of the selected string.
After setting the font, font style, size, and color, etc. on the Font dialog
box, it shows the formatted string, as shown below.
VB.NET Hello World Program
In the previous topic, we have installed Visual Studio 2019 and created a
console-based project with the name MYConsoleApp1. Now in this
project, we will create our Hello world VB.NET program.

A VB.NET define the following structure to create a program:

o Namespace declaration
o Procedure can be multiple
o Define a class or module
o Variables
o The Main procedure
o Statement and Expression
o Comments

Create a Hello_Program.vb file in MYConsoleApp1 project and write the


following code:

Hello_Program.vb

1. Imports System 'System is a Namespace


2. Module Hello_Program
3.
4. Sub Main()
5.
6. Console.WriteLine("Hello, Welcome to the world of VB.NET")
7. Console.WriteLine("Press any key to continue...")
8. Console.ReadKey()
9.
10. End Sub
11.
12.End Module

Let's compile and run the above program by pressing the F5 key, we get
the follwoiing output.

Output:
An Alternate method to compile and execute the
VB.NET program
We can also compile and execute the VB.NET program using the
Command prompt instead of using the Visual Studio IDE.

Step 1: After creating and saving the Hello_Program.vb file in the


MYConsoleApp1 project, open the command prompt and execute the
commands, as we have shown in the prompt.

In place of MYConsoleApp1you can write your project name.

Step 2: After that, write vbc Hello_Program.vb, as shown below.


Step 3: If there is no error found at compile-time, it transfers the control
in the next line for generating the Hello_Pogram.exe file.

Step 4: Type Hello_Program to run the program. We get the following


output.

Output:

Hello, Welcome to the world of VB.NET.

Now we will understand the basic structure of the VB.NET program:

o In VB.NET programming, the first line of the program is "Import System",


where Imports is a statement that inherit the system namespace.
A System is a namespace that contains basic classes, reference data
types, events, attributes, and various inbuilt functions that help to run the
program.
o The Second line defines the Module It specifies the VB.NET filename. As
we know, VB.NET language is a completely object-oriented language, so
every program must contain a module or class in which you can write your
program that contains data and procedures within the module.

1. Module Module1
2. End Module
o You can define more than one procedure in classes and modules.
Generally, the procedure contains executable code to run. A procedure
may contain the following function:
o Function
o Operator
o Sub
o Get
o Set
o AddHandler
o RemoveHandler
o Every program must contain a Main() method. In VB.NET, there is a Main()
method or procedure that represents the starting point to execute a
program, as we have seen in C language, their entry point is the main()
function.
o A comment (') symbol is used to comment on a line that is ignored by the
compiler in a program, and it is a good practice to use comments for a
better understanding of the program.
o The Console.WriteLine() is a method of the console class. It is used to print
any text or messages in the application. And the Console.ReadKey() is
used to read a single character from the keyboard back to the Visual
Studio IDE.

Create a VB.NET program using Windows Form


If you want to create a new Window-based project in Visual Studio, follow
the steps given below:

Step 1. Start the Visual Studio IDE.

Step 2. To create a project, click on File -> choose-> New-> Project


The following window appears on the screen.

Step 3: Select Windows Forms App (.NET Framework) and click on


the Next button.
Step 4: Provide the Project name and location to store the project file
using the browse button in Location.
Step 5: Click on the Create button. The following window appears on the
screen.

Step 6: Now double click on the middle area of Form1.vb (Design) file, it
shows the following code.

Form1.vb

1. Public Class Form1


2. Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyB
ase.Load
3. MsgBox("Welcome to the JavaTpoint")
4. End Sub
5. End Class

Step7: Save file as Form1.vb.

Step 8: To compile and run the Form1.vb file, press F5 button or Start
button in Visual Studio. It shows the following output.

forms and menus : Adding multiple forms in VB, Hiding & showing forms, Load
& unload statements, creating menu, submenu, popup menus, Activate &
deactivate events, Form-load event, menu designing in VB Simple programs in
VB.

Let's start with creating a Window Forms Application by following the


following steps in Microsoft Visual Studio - File → New Project → Windows
Forms Applications

Finally, select OK, Microsoft Visual Studio creates your project and displays
following window Form with a name Form1.
Visual Basic Form is the container for all the controls that make up the user
interface. Every window you see in a running visual basic application is a
form, thus the terms form and window describe the same entity. Visual Studio
creates a default form for you when you create a Windows Forms
Application.

Every form will have title bar on which the form's caption is displayed and
there will be buttons to close, maximize and minimize the form shown below

If you click the icon on the top left corner, it opens the control menu, which
contains the various commands to control the form like to move control from
one place to another place, to maximize or minimize the form or to close the
form.

Form Properties
Following table lists down various important properties related to a form.
These properties can be set or read during application execution. You can
refer to Microsoft documentation for a complete list of properties associated
with a Form control −

S.
Properties Description
N

The button that's automatically activated when you press Enter, no


1 AcceptButton matter which control has the focus at the time. Usually the OK
button on a form is set as AcceptButton for a form.

The button that's automatically activated when you hit the Esc key.
2 CancelButton Usually, the Cancel button on a form is set as CancelButton for a
form.

3 AutoScale This Boolean property determines whether the controls you place
on the form are automatically scaled to the height of the current
font. The default value of this property is True. This is a property of
the form, but it affects the controls on the form.

This Boolean property indicates whether scroll bars will be


4 AutoScroll automatically attached to the form if it is resized to a point that not
all its controls are visible.

AutoScrollMinSiz This property lets you specify the minimum size of the form, before
5
e the scroll bars are attached.

AutoScrollPositio The AutoScrollPosition is the number of pixels by which the two


6
n scroll bars were displaced from their initial locations.

7 BackColor Sets the form background color.

The BorderStyle property determines the style of the form's border


and the appearance of the form −
 None − Borderless window that can't be resized.
 Sizable − This is default value and will be used for
resizable window that's used for displaying regular forms.
 Fixed3D − Window with a visible border, "raised"
relative to the main area. In this case, windows can't be
resized.
8 BorderStyle  FixedDialog − A fixed window, used to create dialog
boxes.
 FixedSingle − A fixed window with a single line border.
 FixedToolWindow − A fixed window with a Close
button only. It looks like the toolbar displayed by the
drawing and imaging applications.
 SizableToolWindow − Same as the
FixedToolWindow but resizable. In addition, its caption font
is smaller than the usual.

By default, this property is True and you can set it to False to hide
9 ControlBox
the icon and disable the Control menu.

If True, allows the form to respond to mouse and keyboard events;


10 Enabled
if False, disables form.

11 Font This property specify font type, style, size

Determines whether a Help button should be displayed in the


12 HelpButton
caption box of the form.

13 Height This is the height of the Form in pixels.

By default, this property is True and you can set it to False to hide
14 MinimizeBox
the Minimize button on the title bar.

By default, this property is True and you can set it to False to hide
15 MaximizeBox
the Maximize button on the title bar.
This specifies the minimum height and width of the window you
16 MinimumSize
can minimize.

This specifies the maximum height and width of the window you
17 MaximumSize
maximize.

18 Name This is the actual name of the form.

This property determines the initial position of the form when it's
first displayed. It will have any of the following values −
 CenterParent − The form is centered in the area of its
parent form.
 CenterScreen − The form is centered on the monitor.
 Manual − The location and size of the form will
19 StartPosition
determine its starting position.
 WindowsDefaultBounds − The form is positioned
at the default location and size determined by Windows.
 WindowsDefaultLocation − The form is positioned
at the Windows default location and has the dimensions
you've set at design time.

20 Text The text, which will appear at the title bar of the form.

These two properties set or return the coordinates of the form's top-
21 Top, Left
left corner in pixels.

This property is a True/False value that lets you specify whether the
22 TopMost form will remain on top of all other forms in your application. Its
default property is False.

23 Width This is the width of the form in pixel.

Form Methods
The following are some of the commonly used methods of the Form class. You
can refer to Microsoft documentation for a complete list of methods
associated with forms control −

Sr.No
Method Name & Description
.

Activate
1
Activates the form and gives it focus.

ActivateMdiChild
2
Activates the MDI child of a form.

3 AddOwnedForm
Adds an owned form to this form.

BringToFront
4
Brings the control to the front of the z-order.

CenterToParent
5
Centers the position of the form within the bounds of the parent form.

CenterToScreen
6
Centers the form on the current screen.

Close
7
Closes the form.

Contains
8
Retrieves a value indicating whether the specified control is a child of the control.

Focus
9
Sets input focus to the control.

Hide
10
Conceals the control from the user.

Refresh
11 Forces the control to invalidate its client area and immediately redraw itself and any child
controls.

Scale(SizeF)
12
Scales the control and all child controls by the specified scaling factor.

ScaleControl
13
Scales the location, size, padding, and margin of a control.

ScaleCore
14
Performs scaling of the form.

Select
15
Activates the control.

SendToBack
16
Sends the control to the back of the z-order.

SetAutoScrollMargin
17
Sets the size of the auto-scroll margins.

SetDesktopBounds
18
Sets the bounds of the form in desktop coordinates.

SetDesktopLocation
19
Sets the location of the form in desktop coordinates.
SetDisplayRectLocation
20
Positions the display window to the specified value.

Show
21
Displays the control to the user.

ShowDialog
22
Shows the form as a modal dialog box.

Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.

Form Events
Following table lists down various important events related to a form. You can
refer to Microsoft documentation for a complete list of events associated with
forms control −

Sr.No
Event Description
.

1 Activated Occurs when the form is activated in code or by the user.

2 Click Occurs when the form is clicked.

3 Closed Occurs before the form is closed.

4 Closing Occurs when the form is closing.

5 DoubleClick Occurs when the form control is double-clicked.

6 DragDrop Occurs when a drag-and-drop operation is completed.

7 Enter Occurs when the form is entered.

8 GotFocus Occurs when the form control receives focus.

HelpButtonClicke
9 Occurs when the Help button is clicked.
d

10 KeyDown Occurs when a key is pressed while the form has focus.

11 KeyPress Occurs when a key is pressed while the form has focus.

12 KeyUp Occurs when a key is released while the form has focus.

13 Load Occurs before a form is displayed for the first time.

14 LostFocus Occurs when the form loses focus.


Occurs when the mouse pointer is over the form and a mouse
15 MouseDown
button is pressed.

16 MouseEnter Occurs when the mouse pointer enters the form.

17 MouseHover Occurs when the mouse pointer rests on the form.

18 MouseLeave Occurs when the mouse pointer leaves the form.

19 MouseMove Occurs when the mouse pointer is moved over the form.

Occurs when the mouse pointer is over the form and a mouse
20 MouseUp
button is released.

Occurs when the mouse wheel moves while the control has
21 MouseWheel
focus.

22 Move Occurs when the form is moved.

23 Resize Occurs when the control is resized.

24 Scroll Occurs when the user or code scrolls through the client area.

25 Shown Occurs whenever the form is first displayed.

26 VisibleChanged Occurs when the Visible property value changes.

Example
Following is an example, which shows how we create two buttons at the time
of form load event and different properties are being set at the same time.

Because Form1 is being referenced within its own event handler, so it will be
written as Me instead of using its name, but if we access the same form
inside any other control's event handler, then it will be accessed using its
name Form1.

Let's double click on the Form and put the follow code in the opened window.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
' Create two buttons to use as the accept and cancel
buttons.
Dim button1 As New Button()
Dim button2 As New Button()
' Set the text of button1 to "OK".

button1.Text = "OK"
' Set the position of the button on the form.
button1.Location = New Point(10, 10)
' Set the text of button2 to "Cancel".

button2.Text = "Cancel"
' Set the position of the button based on the location of
button1.
button2.Location = _
New Point(button1.Left, button1.Height + button1.Top +
10)
' Set the caption bar text of the form.

Me.Text = "tutorialspoint.com"
' Display a help button on the form.
Me.HelpButton = True
' Define the border style of the form to a dialog box.

Me.FormBorderStyle = FormBorderStyle.FixedDialog
' Set the MaximizeBox to false to remove the maximize box.
Me.MaximizeBox = False
' Set the MinimizeBox to false to remove the minimize box.

Me.MinimizeBox = False
' Set the accept button of the form to button1.
Me.AcceptButton = button1
' Set the cancel button of the form to button2.

Me.CancelButton = button2
' Set the start position of the form to the center of the
screen.
Me.StartPosition = FormStartPosition.CenterScreen
' Set window width and height

Me.Height = 300
Me.Width = 560
' Add button1 to the form.

Me.Controls.Add(button1)
' Add button2 to the form.
Me.Controls.Add(button2)
End Sub
End Class

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −
An object is a type of user interface element you create on a Visual Basic
form by using a toolbox control. In fact, in Visual Basic, the form itself is an
object. Every Visual Basic control consists of three important elements −

 Properties which describe the object,


 Methods cause an object to do something and
 Events are what happens when an object does something.

Control Properties
All the Visual Basic Objects can be moved, resized or customized by setting
their properties. A property is a value or characteristic held by a Visual Basic
object, such as Caption or Fore Color.

Properties can be set at design time by using the Properties window or at run
time by using statements in the program code.

Object. Property = Value

Where

 Object is the name of the object you're customizing.


 Property is the characteristic you want to change.
 Value is the new property setting.

For example,

Form1.Caption = "Hello"

You can set any of the form properties using Properties Window. Most of the
properties can be set or read during application execution. You can refer to
Microsoft documentation for a complete list of properties associated with
different controls and restrictions applied to them.
Control Methods
A method is a procedure created as a member of a class and they cause an
object to do something. Methods are used to access or manipulate the
characteristics of an object or a variable. There are mainly two categories of
methods you will use in your classes −

 If you are using a control such as one of those provided by the Toolbox,
you can call any of its public methods. The requirements of such a
method depend on the class being used.
 If none of the existing methods can perform your desired task, you can
add a method to a class.

For example, the MessageBox control has a method named Show, which is
called in the code snippet below −

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs)
Handles Button1.Click
MessageBox.Show("Hello, World")
End Sub
End Class

Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.

Control Events
An event is a signal that informs an application that something important has
occurred. For example, when a user clicks a control on a form, the form can
raise a Click event and call a procedure that handles the event. There are
various types of events associated with a Form like click, double click, close,
load, resize, etc.

Following is the default structure of a form Load event handler subroutine.


You can see this code by double clicking the code which will give you a
complete list of the all events associated with Form control −

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load
'event handler code goes here
End Sub

Here, Handles MyBase.Load indicates that Form1_Load() subroutine


handles Load event. Similar way, you can check stub code for click, double
click. If you want to initialize some variables like properties, etc., then you will
keep such code inside Form1_Load() subroutine. Here, important point to
note is the name of the event handler, which is by default Form1_Load, but
you can change this name based on your naming convention you use in your
application programming.

Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user
interface. Functionalities of all these controls are defined in the respective
control classes. The control classes are defined in
the System.Windows.Forms namespace.

The following table lists some of the commonly used controls −

Sr.No
Widget & Description
.

Forms
1
The container for all the controls that make up the user interface.

TextBox
2
It represents a Windows text box control.

Label
3
It represents a standard Windows label.

Button
4
It represents a Windows button control.

ListBox
5
It represents a Windows control to display a list of items.

ComboBox
6
It represents a Windows combo box control.

RadioButton
7 It enables the user to select a single option from a group of choices when paired with other
RadioButton controls.

CheckBox
8
It represents a Windows CheckBox.

PictureBox
9
It represents a Windows picture box control for displaying an image.

ProgressBar
10
It represents a Windows progress bar control.
ScrollBar
11
It Implements the basic functionality of a scroll bar control.

DateTimePicker
12 It represents a Windows control that allows the user to select a date and a time and to
display the date and time with a specified format.

TreeView
13
It displays a hierarchical collection of labeled items, each represented by a TreeNode.

ListView
14 It represents a Windows list view control, which displays a collection of items that can be
displayed using one of four different views.

There are many built-in dialog boxes to be used in Windows forms for various
tasks like opening and saving files, printing a page, providing choices for
colors, fonts, page setup, etc., to the user of an application. These built-in
dialog boxes reduce the developer's time and workload.

All of these dialog box control classes inherit from the CommonDialog class
and override the RunDialog() function of the base class to create the specific
dialog box.

The RunDialog() function is automatically invoked when a user of a dialog box


calls its ShowDialog() function.

The ShowDialog method is used to display all the dialog box controls at run-
time. It returns a value of the type of DialogResult enumeration. The values
of DialogResult enumeration are −

 Abort − returns DialogResult.Abort value, when user clicks an Abort


button.
 Cancel − returns DialogResult.Cancel, when user clicks a Cancel
button.
 Ignore − returns DialogResult.Ignore, when user clicks an Ignore
button.
 No − returns DialogResult.No, when user clicks a No button.
 None − returns nothing and the dialog box continues running.
 OK − returns DialogResult.OK, when user clicks an OK button
 Retry − returns DialogResult.Retry , when user clicks an Retry button
 Yes − returns DialogResult.Yes, when user clicks an Yes button

The following diagram shows the common dialog class inheritance −


All these above-mentioned classes have corresponding controls that could be
added from the Toolbox during design time. You can include relevant
functionality of these classes to your application, either by instantiating the
class programmatically or by using relevant controls.

When you double click any of the dialog controls in the toolbox or drag the
control onto the form, it appears in the Component tray at the bottom of the
Windows Forms Designer, they do not directly show up on the form.

The following table lists the commonly used dialog box controls. Click the
following links to check their detail −

Sr.No
Control & Description
.

ColorDialog
1 It represents a common dialog box that displays available colors along with controls that
enable the user to define custom colors.

FontDialog
2 It prompts the user to choose a font from among those installed on the local computer and
lets the user select the font, font size, and color.

OpenFileDialog
3
It prompts the user to open a file and allows the user to select a file to open.

SaveFileDialog
4 It prompts the user to select a location for saving a file and allows the user to specify the
name of the file to save data.

PrintDialog
5 It lets the user to print documents by selecting a printer and choosing which sections of the
document to print from a Windows Forms application.

Adding Menus and Sub Menus in an Application


Traditionally, the Menu, MainMenu, ContextMenu, and MenuItem classes were
used for adding menus, sub-menus and context menus in a Windows
application.

Now, the MenuStrip,


the ToolStripMenuItem, ToolStripDropDown and ToolStripDropDownM
enu controls replace and add functionality to the Menu-related controls of
previous versions. However, the old control classes are retained for both
backward compatibility and future use.

Let us create a typical windows main menu bar and sub menus using the old
version controls first since these controls are still much used in old
applications.

Following is an example, which shows how we create a menu bar with menu
items: File, Edit, View and Project. The File menu has the sub menus New,
Open and Save.

Let's double click on the Form and put the following code in the opened
window.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
'defining the main menu bar
Dim mnuBar As New MainMenu()
'defining the menu items for the main menu bar
Dim myMenuItemFile As New MenuItem("&File")
Dim myMenuItemEdit As New MenuItem("&Edit")
Dim myMenuItemView As New MenuItem("&View")
Dim myMenuItemProject As New MenuItem("&Project")

'adding the menu items to the main menu bar


mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)

' defining some sub menus


Dim myMenuItemNew As New MenuItem("&New")
Dim myMenuItemOpen As New MenuItem("&Open")
Dim myMenuItemSave As New MenuItem("&Save")

'add sub menus to the File menu


myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)

'add the main menu to the form


Me.Menu = mnuBar

' Set the caption bar text of the form.


Me.Text = "tutorialspoint.com"
End Sub
End Class

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −

Windows Forms contain a rich set of classes for creating your own custom
menus with modern appearance, look and feel.
The MenuStrip, ToolStripMenuItem, ContextMenuStrip controls are
used to create menu bars and context menus efficiently.

Click the following links to check their details −

Sr.No
Control & Description
.

MenuStrip
1
It provides a menu system for a form.

ToolStripMenuItem
It represents a selectable option displayed on a MenuStrip or ContextMenuStrip.
2
The ToolStripMenuItem control replaces and adds functionality to the MenuItem control of
previous versions.

ContextMenuStrip
3
It represents a shortcut menu.

Adding the Cut, Copy and Paste Functionalities in


a Form
The methods exposed by the ClipBoard class are used for adding the cut,
copy and paste functionalities in an application. The ClipBoard class provides
methods to place data on and retrieve data from the system Clipboard.

It has the following commonly used methods −

Sr.No
Method Name & Description
.

Clear
1
Removes all data from the Clipboard.

ContainsData
2 Indicates whether there is data on the Clipboard that is in the specified format or can be
converted to that format.

ContainsImage
3 Indicates whether there is data on the Clipboard that is in the Bitmap format or can be
converted to that format.

ContainsText
4 Indicates whether there is data on the Clipboard in the Text or UnicodeText format,
depending on the operating system.

GetData
5
Retrieves data from the Clipboard in the specified format.

GetDataObject
6
Retrieves the data that is currently on the system Clipboard.

GetImage
7
Retrieves an image from the Clipboard.

GetText
8 Retrieves text data from the Clipboard in the Text or UnicodeText format, depending on
the operating system.

GetText(TextDataFormat)
9 Retrieves text data from the Clipboard in the format indicated by the specified
TextDataFormat value.

SetData
10
Clears the Clipboard and then adds data in the specified format.

SetText(String)
11 Clears the Clipboard and then adds text data in the Text or UnicodeText format, depending
on the operating system.

Following is an example, which shows how we cut, copy and paste data using
methods of the Clipboard class. Take the following steps −
 Add a rich text box control and three button controls on the form.
 Change the text property of the buttons to Cut, Copy and Paste,
respectively.
 Double click on the buttons to add the following code in the code editor

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
Clipboard.SetDataObject(RichTextBox1.SelectedText)
RichTextBox1.SelectedText = ""
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) _


Handles Button2.Click
Clipboard.SetDataObject(RichTextBox1.SelectedText)
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) _


Handles Button3.Click
Dim iData As IDataObject
iData = Clipboard.GetDataObject()
If (iData.GetDataPresent(DataFormats.Text)) Then
RichTextBox1.SelectedText =
iData.GetData(DataFormats.Text)
Else
RichTextBox1.SelectedText = " "
End If
End Sub
End Class

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −
Enter some text and check how the buttons work.

Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.

Anchoring and Docking Controls in a Form


Anchoring allows you to set an anchor position for a control to the edges of
its container control, for example, the form. The Anchor property of the
Control class allows you to set values of this property. The Anchor property
gets or sets the edges of the container to which a control is bound and
determines how a control is resized with its parent.

When you anchor a control to a form, the control maintains its distance from
the edges of the form and its anchored position, when the form is resized.

You can set the Anchor property values of a control from the Properties
window −
For example, let us add a Button control on a form and set its anchor property
to Bottom, Right. Run this form to see the original position of the Button
control with respect to the form.

Now, when you stretch the form, the distance between the Button and the
bottom right corner of the form remains same.
Docking of a control means docking it to one of the edges of its container. In
docking, the control fills certain area of the container completely.

The Dock property of the Control class does this. The Dock property gets or
sets which control borders are docked to its parent control and determines
how a control is resized with its parent.

You can set the Dock property values of a control from the Properties window

For example, let us add a Button control on a form and set its Dock property
to Bottom. Run this form to see the original position of the Button control with
respect to the form.
Now, when you stretch the form, the Button resizes itself with the form.

Modal Forms
Modal Forms are those forms that need to be closed or hidden before you
can continue working with the rest of the application. All dialog boxes are
modal forms. A MessageBox is also a modal form.

You can call a modal form by two ways −

 Calling the ShowDialog method


 Calling the Show method

Let us take up an example in which we will create a modal form, a dialog box.
Take the following steps −

 Add a form, Form1 to your application, and add two labels and a button
control to Form1
 Change the text properties of the first label and the button to 'Welcome
to Tutorials Point' and 'Enter your Name', respectively. Keep the text
properties of the second label as blank.
 Add a new Windows Form, Form2, and add two buttons, one label, and
a text box to Form2.
 Change the text properties of the buttons to OK and Cancel,
respectively. Change the text properties of the label to 'Enter your
name:'.
 Set the FormBorderStyle property of Form2 to FixedDialog, for giving it
a dialog box border.
 Set the ControlBox property of Form2 to False.
 Set the ShowInTaskbar property of Form2 to False.
 Set the DialogResult property of the OK button to OK and the Cancel
button to Cancel.

Add the following code snippets in the Form2_Load method of Form2 −

Private Sub Form2_Load(sender As Object, e As EventArgs) _


Handles MyBase.Load
AcceptButton = Button1
CancelButton = Button2
End Sub

Add the following code snippets in the Button1_Click method of Form1 −

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
Dim frmSecond As Form2 = New Form2()

If frmSecond.ShowDialog() = DialogResult.OK Then


Label2.Text = frmSecond.TextBox1.Text
End If
End Sub

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −

Clicking on the 'Enter your Name' button displays the second form −

Clicking on the OK button takes the control and information back from the
modal form to the previous form −
Events are basically a user action like key press, clicks, mouse movements,
etc., or some occurrence like system generated notifications. Applications
need to respond to events when they occur.

Clicking on a button, or entering some text in a text box, or clicking on a


menu item, all are examples of events. An event is an action that calls a
function or may cause another event. Event handlers are functions that tell
how to respond to an event.

VB.Net is an event-driven language. There are mainly two types of events −

 Mouse events
 Keyboard events

Handling Mouse Events


Mouse events occur with mouse movements in forms and controls. Following
are the various mouse events related with a Control class −

 MouseDown − it occurs when a mouse button is pressed


 MouseEnter − it occurs when the mouse pointer enters the control
 MouseHover − it occurs when the mouse pointer hovers over the
control
 MouseLeave − it occurs when the mouse pointer leaves the control
 MouseMove − it occurs when the mouse pointer moves over the
control
 MouseUp − it occurs when the mouse pointer is over the control and
the mouse button is released
 MouseWheel − it occurs when the mouse wheel moves and the
control has focus

The event handlers of the mouse events get an argument of


type MouseEventArgs. The MouseEventArgs object is used for handling
mouse events. It has the following properties −

 Buttons − indicates the mouse button pressed


 Clicks − indicates the number of clicks
 Delta − indicates the number of detents the mouse wheel rotated
 X − indicates the x-coordinate of mouse click
 Y − indicates the y-coordinate of mouse click

Example
Following is an example, which shows how to handle mouse events. Take the
following steps −

 Add three labels, three text boxes and a button control in the form.
 Change the text properties of the labels to - Customer ID, Name and
Address, respectively.
 Change the name properties of the text boxes to txtID, txtName and
txtAddress, respectively.
 Change the text property of the button to 'Submit'.
 Add the following code in the code editor window −
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs)
Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub

Private Sub txtID_MouseEnter(sender As Object, e As


EventArgs)_
Handles txtID.MouseEnter
'code for handling mouse enter on ID textbox
txtID.BackColor = Color.CornflowerBlue
txtID.ForeColor = Color.White
End Sub

Private Sub txtID_MouseLeave(sender As Object, e As EventArgs)


_
Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox
txtID.BackColor = Color.White
txtID.ForeColor = Color.Blue
End Sub

Private Sub txtName_MouseEnter(sender As Object, e As


EventArgs) _
Handles txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub

Private Sub txtName_MouseLeave(sender As Object, e As


EventArgs) _
Handles txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White
txtName.ForeColor = Color.Blue
End Sub

Private Sub txtAddress_MouseEnter(sender As Object, e As


EventArgs) _
Handles txtAddress.MouseEnter
'code for handling mouse enter on Address textbox
txtAddress.BackColor = Color.CornflowerBlue
txtAddress.ForeColor = Color.White
End Sub

Private Sub txtAddress_MouseLeave(sender As Object, e As


EventArgs) _
Handles txtAddress.MouseLeave
'code for handling mouse leave on Address textbox
txtAddress.BackColor = Color.White
txtAddress.ForeColor = Color.Blue
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
MsgBox("Thank you " & txtName.Text & ", for your kind
cooperation")
End Sub
End Class

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −

Try to enter text in the text boxes and check the mouse events −
Explore our latest online courses and learn new skills at your own pace.
Enroll and become a certified expert to boost your career.

Handling Keyboard Events


Following are the various keyboard events related with a Control class −

 KeyDown − occurs when a key is pressed down and the control has
focus
 KeyPress − occurs when a key is pressed and the control has focus
 KeyUp − occurs when a key is released while the control has focus

The event handlers of the KeyDown and KeyUp events get an argument of
type KeyEventArgs. This object has the following properties −

 Alt − it indicates whether the ALT key is pressed


 Control − it indicates whether the CTRL key is pressed
 Handled − it indicates whether the event is handled
 KeyCode − stores the keyboard code for the event
 KeyData − stores the keyboard data for the event
 KeyValue − stores the keyboard value for the event
 Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are
pressed
 Shift − it indicates if the Shift key is pressed

The event handlers of the KeyDown and KeyUp events get an argument of
type KeyEventArgs. This object has the following properties −

 Handled − indicates if the KeyPress event is handled


 KeyChar − stores the character corresponding to the key pressed
Example
Let us continue with the previous example to show how to handle keyboard
events. The code will verify that the user enters some numbers for his
customer ID and age.

 Add a label with text Property as 'Age' and add a corresponding text
box named txtAge.
 Add the following codes for handling the KeyUP events of the text box
txtID.
Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtID.KeyUp

If (Not Char.IsNumber(ChrW(e.KeyCode))) Then


MessageBox.Show("Enter numbers for your Customer ID")
txtID.Text = " "
End If
End Sub
 Add the following codes for handling the KeyUP events of the text box
txtID.
Private Sub txtAge_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtAge.KeyUp

If (Not Char.IsNumber(ChrW(e.keyCode))) Then


MessageBox.Show("Enter numbers for age")
txtAge.Text = " "
End If
End Sub

When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −
If you leave the text for age or ID as blank or enter some non-numeric data, it
gives a warning message box and clears the respective text −

You might also like