Notes
Notes
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.
End Sub
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 −
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.
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:
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.
Toolbar
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 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 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.
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.
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:
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.
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”.
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:
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()
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.
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
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
End Sub
End Module
Step 3) Click the Start button to execute the code. You should get the following
window:
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:
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.
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.
Sub Main()
The Binary XOR Operator. For copying a bit if set in one of the
Xor
operands rather than both.
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
End Sub
End Module
Step 3) Run the code by clicking the Start button. You should get the following
window:
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.
Syntax:
Name Descriptions
Dim It is used to declare and allocate the space for one or more variable
memory.
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.
There are some valid declarations of variables along with their data type
definition, as shown below:
Further, if we want to declare more than one variable in the same line,
we must separate each variable with a comma.
Syntax
Note: The statements given below is also used to declare the variable with their data
type:
Syntax:
1. Variable_name = value
For example:
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:
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:
Example:
1. Dim x As Integer
2. 10 = x
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:
Item Descriptions
Name
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.
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:
Note: The statements given below are also used to declare the variable with their data
type:
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
1. Procedure Scope
2. Module Scope
3. Public Scope
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:
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.
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:
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:
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
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.
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
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_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.
< 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.
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.
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:
And The And Operator represents, whether both the (A And B),
operands are true; the result is True. result =
False
Not(A And B)
is True
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.
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.
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.
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.
&= 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.
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:
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
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
-
Await Highest
Exponential ^
Integer division \
All comparison Operators =, <>, <, <=, >, >=, Is, IsNot,
Like, TypeOf …is
Negation Not
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:
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.
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
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.
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:
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.
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
Furthermore, you can also set more than one condition in a single case statement, such as:
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.
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.
Syntax:
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
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:
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
For example:
and
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.
If testmsg = 1 Then
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
16 vbCritical
3 vbQuestion
48 vbExclamation
64 vbInformation
Example 12.2
If testMsg = 6 Then
Else
End If
End Sub
The first argument, Prompt, will display the message
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 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:
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
Example 12.3
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
PauseNext
Unmute
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
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
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.
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.
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.
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:
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
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:
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
Furthermore, you can also set more than one condition in a single case
statement, such as:
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.
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.
Syntax:
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:
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:
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:
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:
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:
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:
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
0 vbOkOnly Ok button
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.
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
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
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:
End Sub
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:
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
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.
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
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.
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.
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: ")
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.
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)
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.
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
'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
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
'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
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
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub
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.
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
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
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 −
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 −
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.
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.
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
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.
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
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 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.
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.
Properties Description
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.
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
Output:
Click on the File menu that shows the multiple options related to files.
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.
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
Form3.vb
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
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 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
Output:
Now, click on the Click Me button of the Windows Form, it displays the
dialog box, as shown below.
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.
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
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.
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.
Let's create a simple program to display the Color dialog box in the
VB.NET Windows Forms.
ColorDialog.vb
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 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.
Equals() The Equals() method is used to check whether the current or defined obje
the same.
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.
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
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
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.
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
Hello_Program.vb
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.
Output:
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.
Step 6: Now double click on the middle area of Form1.vb (Design) file, it
shows the following code.
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.
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 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.
AutoScrollMinSiz This property lets you specify the minimum size of the form, before
5
e the scroll bars are attached.
By default, this property is True and you can set it to False to hide
9 ControlBox
the icon and disable the Control menu.
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.
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.
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
.
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.
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.
24 Scroll Occurs when the user or code scrolls through the client area.
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.
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 −
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.
Where
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 −
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.
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.
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 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 −
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.
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.
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.
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.
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
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.
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.
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.
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.
Mouse events
Keyboard events
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
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.
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 −
The event handlers of the KeyDown and KeyUp events get an argument of
type KeyEventArgs. This object has the following properties −
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
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 −