Visual Basic Merged
Visual Basic Merged
Visual Basic (VB) is an event-driven programming language and environment from Microsoft that provides
a graphical user interface (GUI) which allows programmers to modify code by simply dragging and
dropping objects and defining their behavior and appearance. VB is derived from the BASIC programming
language and is considered to be event-driven and object-oriented.
VB is intended to be easy to learn and fast to write code with; as a result, it is sometimes called a rapid
application development (RAD) system and is used to prototype an application that will later be written in a
more difficult but efficient language.
The last version of VB, Visual Basic 6, was released in 1998, but has since been replaced by VB .NET,
Visual Basic for applications (VBA) and Visual Stuido .NET. VBA and Visual Studio are the two frameworks
most commonly used today.
Visual Basic was designed to be a complete programming language that contained ordinary features, such
as string processing and computation. The visual environment is characterized by a drag-and-drop feature which
allows programmers to build a user interface that is easy to use, even for developers with minimum experience.
While these features of VB are advantageous, there are others that can have a negative effect. The VB programming
environment requires a large amount of memory, both for the initial installation and to run efficiently afterwards. The
graphical features of the programming tool take up a large amount of space and require a significant amount of
memory.
Furthermore, Visual Basic is not useful when developing programs that require a lot of processing time, like games,
and the use of VB is restricted to Microsoft operating systems (OS).
Finally, with C languages, programmers can feasibly locate and use the defined values for variable data in a computer
program at declaration time. This initialization practice is something that isn't easily done with VB.
The most popular type of Visual Basic in use today is VBA. VBA is a version of Visual Basic that can be used to
program Microsoft Office apps, such as Excel and PowerPoint. However, it can only be used to modify existing apps;
VBA cannot be used to create new apps.
Typical users engage VBA to make repeated, everyday tasks less monotonous through the use of macros. Macros
automate almost any activity -- such as performing word and data processing or generating custom charts and tables.
For example, a typical user might write a macro that allows them to create and fill a spreadsheet with a single click.
Computer professionals use VBA and macros in more complicated ways. Programmers will often write macros that
can replicate large portions of code or define specific languages.
Businesses and organizations can use VBA to customize Excel for their unique purposes, such as pulling certain
statistics or information from a spreadsheet. Businesses and organizations can also use VBA externally, or in non-
Microsoft applications, by applying a technology called a component object model (COM) interface that enables
commands to communicate across computer boundaries. This allows VBA to be used on an enterprise-specific
application.
However, VB becomes extremely beneficial when used with Microsoft's COM interface. The COM components can
be written in various languages and then integrated using VB. Additionally, VB provides not only a programming
language, but an integrated development environment (IDE) that has been written and optimized to best support RAD.
This allows programmers to easily build GUIs and connect them to functions within the application.
Furthermore, the Visual Basic IDE provides views of the management of the program structure that are easy to
understand.
Overall, VB enables the rapid development of Windows based applications while also assisting in the access of
databases by using ActiveX data objects (ADO) while allowing programmers to use ActiveX control and various
objects.
Difference Between VB.NET and Visual Basic
VB.NET stands for Visual Basic. Network Enabled Technologies. Microsoft released the .NET
platform in 2001, that supports Visual Basic .NET which is an upgrade to the last version of VB
programming language. It is a high-level programming language for the Microsoft .NET
Framework. It is also possible to run VB.NET on Linux and MAC operating systems.
Visual Basic or VB is a programming language was initially released in 1991. It was the first
programming language that directly supported programmable graphical user interface using
language-supplied objects. From that time until 2002, there were 7 other versions released, each
version having features that increased the power of the language.
Programming
VB.NET is an object-oriented Visual Basic is Event Driven
Language
programming language. programming language.
Paradigm
It is a compiled typed
It is an Interpreter based language
Type language
Visual Programming :
Non Visual Programming does not require IDE : Integrated Development Environment.
In Non Visual Programming, there is no IDE, so developer has to be master in language
syntax & fast typing as well for the fast development.
Non Visual Programming does not provide such features.
In Non Visual Programming, you have to create programme textually, no GUI is there,
only Text based interface.
With Non Visual Programming, You have to write down programme in the form of text only.
Non Visual programming is difficult but also increase you memory power and logic.
Differences between Procedural and Object
Oriented Programming
Procedural Programming
Object-Oriented Programming
Object-oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of
methods. In object-oriented programming, computer programs are designed using the concept of
objects that interact with the real world. Object-oriented programming languages are various but
the most popular ones are class-based, meaning that objects are instances of classes, which
also determine their types.
Languages used in Object-Oriented Programming:
Below are some of the differences between procedural and object-oriented programming:
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any proper way Object-oriented programming provides data hiding so
of hiding data so it is less secure. it is more secure.
In procedural programming, there is no concept of data In object-oriented programming, the concept of data
hiding and inheritance. hiding and inheritance is used.
Procedural programming is used for designing Object-oriented programming is used for designing
medium-sized programs. large and complex programs.
Procedural programming uses the concept of procedure Object-oriented programming uses the concept of data
abstraction. abstraction.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
What Does Procedural Language Mean?
A procedural language is a type of computer programming language that specifies a series of well-structured steps and
procedures within its programming context to compose a program. It contains a systematic order of statements,
functions and commands to complete a computational task or program.
Calling a Procedure
You invoke a procedure from some other place in the code. This is known as a procedure call. When the
procedure is finished running, it returns control to the code that invoked it, which is known as the calling
code. The calling code is a statement, or an expression within a statement, that specifies the procedure by
name and transfers control to it.
With a Return statement, control returns immediately to the calling code. Statements following
the Return statement do not run. You can have more than one Return statement in the same
procedure.
With an Exit Sub or Exit Function statement, control returns immediately to the calling code.
Statements following the Exit statement do not run. You can have more than one Exit statement in
the same procedure, and you can mix Return and Exit statements in the same procedure.
If a procedure has no Return or Exit statements, it concludes with an End Sub or End Function, End Get,
or End Set statement following the last statement of the procedure body. The End statement returns
control immediately to the calling code. You can have only one End statement in a procedure.
Sub Procedures perform actions but do not return a value to the calling code.
Event-handling procedures are Sub procedures that execute in response to an event raised by user
action or by an occurrence in a program.
Function Procedures return a value to the calling code. They can perform other actions before
returning.
Some functions written in C# return a reference return value. Function callers can modify the return
value, and this modification is reflected in the state of the called object. Starting with Visual Basic 2017,
Visual Basic code can consume reference return values, although it cannot return a value by reference.
For more information, see Reference return values.
In OOP, data is treated as a critical element and does not allow it to flow freely. It
bounds data closely to the functions that operate on it and protects it from
accidental modification from outside functions. OOP allows decomposition of a
problem into a number of entities called objects and then builds data and
functions around these objects. A major advantage of OOP is code reusability.
Concepts of OOP:
Objects
Classes
Data Abstraction and Encapsulation
Inheritance
Polymorphism
Objects
Inheritance
Inheritance is the process by which objects can acquire the properties of objects of
other class. In OOP, inheritance provides reusability, like, adding additional
features to an existing class without modifying it. This is achieved by deriving a
new class from the existing one. The new class will have combined features of both
the classes.
Polymorphism
Polymorphism means the ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behavior depends on the data
types used in the operation. Polymorphism is extensively used in implementing
Inheritance.
Classes are types and Objects are instances of the Class. Classes and Objects are
very much related to each other. Without objects you can't use a class. In Visual
Basic we create a class with the Class statement and end it with End Class. The
Syntax for a Class looks as follows:
Code:
Public Class Test
Variables
Methods
Properties
Events
End Class
The above syntax created a class named Test. To create a object for this class we
use the new keyword and that looks like this: Dim obj as new Test().
Fields, Properties, Methods, and Events are members of the class. They can be
declared as Public, Private, Protected, Friend or Protected Friend. Fields and
Properties represent information that an object contains. Fields of a class are like
variables and they can be read or set directly. For example, if you have an object
named House, you can store the numbers of rooms in it in a field named Rooms. It
looks like this:
Code:
Public Class House
Public Rooms as Integer
End Class
Properties are retrieved and set like fields but are implemented using Property Get
and Property Set procedures which provide more control on how values are set or
returned. Methods represent the object’s built-in procedures. Events allow objects
to perform actions whenever a specific occurrence takes place.
Constructors
Destructors
A destructor, also know as finalizer, is the last method run by a class. Within a
destructor we can place code to clean up the object after it is used, which might
include decrementing counters or releasing resources. We use Finalize method in
Visual Basic for this and the Finalize method is called automatically when the
.NET runtime determines that the object is no longer required.
When working with destructors we need to use the overrides keyword with Finalize
method as we will override the Finalize method built into the Object class. We
normally use Finalize method to deallocate resources and inform other objects that
the current object is going to be destroyed. Because of the nondeterministic nature
of garbage collection, it is very hard to determine when a class's destructor will be
called.
Inheritance
A key feature of OOP is reusability. It's always time saving and useful if we can
reuse something that already exists rather than trying to create the same thing
again and again. Reusing the class that is tested, debugged and used many times
can save us time and effort of developing and testing it again. Once a class has
been written and tested, it can be used by other programs to suit the program's
requirement. This is done by creating a new class from an existing class. The
process of deriving a new class from an existing class is called Inheritance. The old
class is called the base class and the new class is called derived class. The derived
class inherits some or everything of the base class. In Visual Basic we use the
Inherits keyword to inherit one class from other. The general form of deriving a
new class from an existing class looks as follows:
Code:
Public Class One
---
---
End Class
Public Class Two
Inherits One
---
---
End Class
Using Inheritance we can use the variables, methods, properties, etc, from the base
class and add more functionality to it in the derived class.
Polymorphism
Polymorphism is one of the crucial features of OOP. It means "one name, multiple
forms". It is also called as Overloading which means the use of same thing for
different purposes. Using Polymorphism we can create as many functions we want
with one function name but with different argument list. The function performs
different operations based on the argument list in the function call. The exact
function to be invoked will be determined by checking the type and number of
arguments in the function.
Code:
Module Module1
Sub Main()
Dim two As New One()
WriteLine(two.add(10))
'calls the function with one argument
WriteLine(two.add(10, 20))
'calls the function with two arguments
WriteLine(two.add(10, 20, 30))
'calls the function with three arguments
Read()
End Sub
End Module
Public Class One
Public i, j, k As Integer
Public Function add(ByVal i As Integer) As Integer
'function with one argument
Return i
End Function
Public Function add(ByVal i As Integer, ByVal j As Integer) As Integer
'function with two arguments
Return i + j
End Function
Public Function add(ByVal i As Integer, ByVal j As Integer, ByVal k As Integer) As Integer
'function with three arguments
Return i + j + k
End Function
End Class
Interfaces
Abstract Classes
An abstract class is the one that is not used to create objects. An abstract class is
designed to act as a base class (to be inherited by other classes). Abstract class is a
design concept in program development and provides a base upon which other
classes are built. Abstract classes are similar to interfaces. After declaring an
abstract class, it cannot be instantiated on it's own, it must be inherited. Like
interfaces, abstract classes can specify members that must be implemented in
inheriting classes. Unlike interfaces, a class can inherit only one abstract class.
Abstract classes can only specify members that should be implemented by all
inheriting classes.
Structures
Structures can be defined as a tool for handling a group of logically related data
items. They are user-defined and provide a method for packing together data of
different types. Structures are very similar to Classes. Like Classes, they too can
contain members such as fields and methods. The main difference between classes
and structures is, classes are reference types and structures are value types. In
practical terms, structures are used for smaller lightweight objects that do not
persist for long and classes are used for larger objects that are expected to exist in
memory for long periods. We declare a structure in Visual Basic .NET with the
Structure keyword.
Value Types and Reference Types belong to Application data memory and the
difference between them is the way variable data is accessed. In VB .NET we use
the Dim statement to create a variable that represents a value type. For example,
we declare a integer variable with the following statement: Dim x as Integer. The
statement tells the run time to allocate the appropriate amount of memory to hold
an integer variable. The statement creates a variable but does not assign a value to
it. We assign a value to that variable like this: x=55. When a variable of value type
goes out of scope, it is destroyed and it's memory is reclaimed.
Reference Types
1. Click
2. MouseMove
3. KeyPress
In Visual Basic, the strength of any graphical or non-graphical control is measured by the kind of special events it
provides to a program.
Procedural Programming can be defined as a programming model which is derived from structured
programming, based upon the concept of calling procedure. Procedures, also known as routines,
subroutines or functions, simply consist of a series of computational steps to be carried out. During
a program’s execution, any given procedure might be called at any point, including by other
procedures or itself.
Object oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of methods.
In object oriented programming, computer programs are designed using the concept of objects that
interact with real world. Object oriented programming languages are various but the most popular
ones are class-based, meaning that objects are instances of classes, which also determine their
types.
Languages used in Object Oriented Programming:Java, C++, C#, Python, PHP, JavaScript.
In object oriented programming, program is divided into small parts called objects.
Object oriented programming follows bottom up approach.
Object oriented programming have access specifiers like private, public, protected etc.
Adding new data and function is easy.
Object oriented programming provides data hiding so it is more secure.
Overloading is possible in object oriented programming.
In object oriented programming, data is more important than function.
Object oriented programming is based on real world.
Examples: C++, Java, Python, C# etc.
Events are monitored by a code (or function) known as an event listener. If the event listener
detects that an assigned event has occurred, it will trigger a callback function, known as an event
handler, which will perform said event, e.g. clicking (the event) a “print” button (event listener)
activates the actual print process (event handler).
Virtually all object-oriented and visual languages support event-driven programming. Visual Basic,
Visual C++ and Java are examples of such languages. A visual programming IDE such as VB.Net
provides much of the code for detecting events automatically when a new application is created.
The Visual Basic Environment
Welcome to the third Article in our Visual Basic section. Last week we installed Visual Basic. This
week we will be looking at the environment that you are presented with when you start Visual
Basic, and set a few options that will prepare Visual Basic to meet our demands.
Let’s run Visual Basic for the very first time. The first thing you will see is this screen, where you are
presented with a list of various project templates.
For now, select Standard EXE, and click on Open. The next Visual Basic will add a few things for
you, to accomplish the standard setup it needs for creating a Standard Executable (Which
eventually will be a runnable program with a .exe extension).
The screen you see now will look more or less similar to this one.
Wow. That’s a lot of weird windows. Let’s go through them one by one. In the lower-right corner,
you will see the Form Layout window.
Using the Form Layout Window, you can choose where your program will essentially show up once
it is completed. As you can see, it already contains a small version of a form, which can be moved
around the screen.
Right-clicking the Form Layout Window will also give you the possibility to select some positions
(In the ‘Startup Position’-sub menu). The Form Layout Window is not something we will be using
often. (Well, I don’t use it often. It’s up to you to decide whether or not you leave it visible, or just
hide it).
The window right above the Form Layout Window is the Properties Window.
This is one of the windows you will probably use a lot. It shows the properties of the currently
selected object. What is a property, you ask? The definition from MSDN is: “A property is a
characteristic of an object, such as size, caption, or color”.
Let’s look at this a little more in-depth, shall we? Imagine for a second we’re a God. We created a
world, threw in trees, bushes, and what not; added a few animals, and are now working on tossing
in a few people. Every person has a few characteristics: Eye color, hair color, a name, a shoe-size,
etc. With the Properties Window, you can quickly see all the various properties on objects, and set
or change current properties.
The Properties Window is made up out of three elements (As seen in the picture):
# Object Box
# Sort Tabs
# Property List
The Object box provides a list of objects currently in use in the project, of which you can set
properties.
The Sort Tabs provide a quick way of sorting the Property List. You can sort either by category, or
alphabetically. This is really a matter of choice, or habit. Use whichever way you prefer.
The Property List provides a list of all the properties that can be set for the currently selected object.
The left column provides the property name, the right column shows the currently assigned value.
Under the Property List, a short description of the currently selected property is displayed. (You
can turn this off by right-clicking the Property Window, and unchecking the Description option).
Above the Properties Window, we’ll find our good friend the Project Explorer.
The Project Explorer shows the different files that make up your project. Notice that in the above
screen shot, I added a few extra files, to show a more extensive window than the one you will
currently see.
On the left side of the screen, you will find the toolbox.
The Toolbox
The toolbox holds various ActiveX controls that you can use in your projects. In addition to the
standard ones you already see, you can also add other controls (that could be provided by
Microsoft, third-parties, or controls that you made yourself).
In the middle of the screen, you will find the Form Designer.
The Form Designer shows you the interface of your application. You can use the Form Designer to
determine exactly what your project is going to look like, which controls will be available, which
text will be displayed where, etc, etc.
This leaves us with two more things to discuss concerning the interface. The toolbar, and the menu,
both of which have a lot in common with standard Windows applications, but offer a few new
functions. Let’s tackle the toolbar first.
The Toolbar
The Toolbar provides a number of icons, some of which you will undoubtedly recognize from
programs as Word, or any other Windows Application.
We’ll briefly describe the various icons here, but won’t go deeper into what they do for now, as we
will get working with that gradually, as we advance more and more into the actual programming
process. You can get little description-labels by hovering the cursor over the icon for a second.
The first three icons are specific to Visual Basic. The left-most one allows you to add other projects
to the project you’re working on, the middle icon adds files to your project, and the right-most one
allows you to create user-menus.
The next few ought to look rather familiar to anyone who worked with Windows before. The first
icon is for Opening a file, the second one for saving a file. The third icon is for cutting, the fourth
one for copying, the fifth one for pasting, and the sixth one is for searching. The two arrows on the
far right are respectively for undoing and redoing operations.
Three VB-specific icons again. They might look familiar however. They highly resemble buttons as
they are used on Stereo / Video equipment. They provide the same functionality as well. The first
one runs a project, the second one pauses it, and the third one aborts (or stops) the project.
These icons are all short-cuts to the various windows we discussed earlier. The first one is the
Project Explorer, the second one the Properties Window, the third one represents the Form Layout
Window.
The fourth one is a new one. It points to the Object Browser which we will discuss in future articles.
The fifth icon is for the Toolbox, and the sixth is a new one again. It points to the Data View
Window, which we will discuss when we get to the article about Connectivity to Databases. (Which
will be a few weeks from now).
The right-most icon the Visual Component Manager; basically a repository database for storing
reusable bits and pieces of code, files, components, etc in.
The last part of the toolbar is for keeping track of the position and size of controls. The leftmost part
is for the position, while the right part lists the size of a control. To see what both do, double-click
on one of the icons on the toolbar, which will make a control be added to your form. Rezise and
move the control on the form, and the numbers will change.
The Menu
The Menu contains a few default Windows menu-items (like file, edit, view, help, etc.), and a few
functions specific to programming (like Debug, Run, Project, etc.).
That concludes the description of the environment. I also promised to set a few quick options to
configure Visual Basic, so bear with me for another 5 minutes or so. We’ve done the hardest part;
the next few minutes are peanuts. I’ll just provide the settings here. Why I choose the settings will
be explained in future articles.
Click on Tools, and select Options. We’re going to make sure that we reduce the number of errors
we’re going to have to deal with. On the tab ‘Editor’, check the ‘Require Variable Declaration’ box.
On the ‘General’-tab, I’d recommend selecting the ‘Break on Unhandled Errors’ option. This will
make debugging easier.
That’s it! Thanks for sticking with me for so long. In next week’s article, we will discuss the
standard controls, and include a few of them in a project. We’ll take a look at their common
properties, events, and methods, as well as make our first actual program.
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.
For variable naming rules and considerations, see Declared Element Names.
Declaration Levels
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.
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.
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.
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.
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.
Types of Variables
Visual Basic recognizes the following five categories of variables:
Numeric
String
Boolean
Date
Object
The two major variable categories are numeric and string. Numeric variables store numbers, and string
variables store text. Object variables can store any type of data. Why bother to specify the type if one type
suits all? On the surface, using object variables might seem like a good idea, but they have their
disadvantages. Integer variables are optimized for storing integers, and date variables are optimized for
storing dates. Before VB can use an object variable, it must determine its type and perform the necessary
conversions. If the variable is declared with a specific type, these conversions are not necessary.
We begin our discussion of variable types with numeric variables. Text is stored in string variables, but
numbers can be stored in many formats, depending on the size of the number and its precision. That’s why
there are many types of numeric variables. The String and Date data types are much richer in terms of the
functionality they expose, and are discussed in more detail in Chapter, ‘‘Handling Strings, Characters, and
Dates.”
Numeric Variables
You’d expect that programming languages would use the same data type for numbers. After all, a number
is a number. But this couldn’t be further from the truth. All programming languages provide a variety of
numeric data types, including the following:
Decimals
Decimal, Single, and Double are the three basic data types for storing floating-point numbers (numbers with
a fractional part). The Double data type can represent these numbers more accurately than the Single type
and is used almost exclusively in scientific calculations.
The Integer data types store whole numbers. The data type of your variable can make a difference in the
results of the calculations. The proper variable types are determined by the nature of the values they
represent, and the choice of data type is frequently a trade-off between precision and speed of execution
(less-precise data types are manipulated faster). Visual Basic supports the numeric data types shown in
Table 2.1. In the Data Type column, I show the name of each data type and the corresponding keyword in
parentheses.
Integer Variables
There are three types of variables for storing integers, and they differ only in the range of numbers each
can represent. As you understand, the more bytes a type takes, the larger values it can hold. The type of
Integer variable you’ll use depends on the task at hand. You should choose the type that can represent the
largest values you anticipate will come up in your calculations. You can go for the Long type, to be safe, but
Long variables are four times as large as Short variables, and it takes the computer longer to process them.
The statements in Listing 2.1 will help you understand when to use the various Integer data types. Each
numeric data type exposes the MinValue and MaxValue properties, which return the minimum and
maximum values, respectively, that can be represented by the corresponding data type. Values of the Short
(Int16) type can be stored in Integer (Int32) and Long (Int64) variables, but the reverse is not true. If you
attempt to store a Long value to an Integer variable, an error will be generated and the compiler will
underline the offending line with a wiggly line. I have included comments after each statement to explain the
errors produced by some of the statements.
The next two statements attempt to store to an Integer variable two values that are also outside of the
range that an integer can represent. The first value exceeds the range of positive values, and the second
exceeds the range of negative values. If you attempt to store these values to a Long variable, there will be
no problem. If you exceed the range of values that can be represented by the Long data type, you’re out of
luck. This value can’t be represented as an integer, and you must store it in one of the variable types
discussed in the next sections.
Object Variables
Variants — variables without a fixed data type— were the bread and butter of VB programmers up to
version 6. Variants are the opposite of strictly typed variables: They can store all types of values, from a
single character to an object. If you’re starting with VB 2008, you should use strictly typed variables.
However, variants are a major part of the history of VB, and most applications out there (the ones you may
be called to maintain) use them. I will discuss variants briefly in this section and show you what was so
good (and bad) about them.
Variants, or object variables, were the most flexible data types because they could accommodate all other
types. A variable declared as Object (or a variable that hasn’t been declared at all) is handled by Visual
Basic according to the variable’s current contents. If you assign an integer value to an object variable,
Visual Basic treats it as an integer. If you assign a string to an object variable, Visual Basic treats it as a
string. Variants can also hold different data types in the course of the same program. Visual Basic performs
the necessary conversions for you.
To declare a variant, you can turn off the Strict option and use the Dim statement without specifying a type,
as follows:
MsgBox "We suggest a " & modemSpeed & " modem."Code language: VB.NET (vbnet)
This statement displays the following message:
"A 28.8 modem can transfer 3686.4 bytes per second."Code language: VB.NET (vbnet)
The first instance of the modemSpeed variable in the preceding statement is treated as a string because
this is the variant’s type according to the assignment statement (we assigned a string to it). The second
instance, however, is treated as a number (a single-precision number). Visual Basic converts it to a numeric
value because it’s used in a numeric calculation.
Another example of this behavior of variants can be seen in the following statements:
Visual Basic knows how to handle object variables in a way that makes sense. The result may not be what
you had in mind, but it certainly is dictated by common sense. If you really want to concatenate the strings
10 and 11, you should use the & operator, which would tell Visual Basic exactly what to do. Quite
impressive, but for many programmers, this is a strange behavior that can lead to subtle errors — and they
avoid it. It’s up to you to decide whether to use variants and how far you will go with them. Sure, you can
perform tricks with variants, but you shouldn’t overuse them to the point that others can’t read your code.
Date Variables
Date and time values are stored internally in a special format, but you don’t need to know the exact format.
They are double-precision numbers: the integer part represents the date, and the fractional part represents
the time. A variable declared as Date with a statement like the following can store both date and time
values:
The pound sign tells Visual Basic to store a date value to the expiration variable, just as the quotes tell
Visual Basic that the value is a string. You can store a date as a string to a Date variable, but it will be
converted to the appropriate format. If the Strict option is on, you can’t specify dates by using the Long date
format (as in the third statement of this example).
The date format is determined by the Regional Settings (found in the Control Panel). In the United States,
the format is mm/dd/yy. (In other countries, the format is dd/mm/yy.) If you assign an invalid date to a date
variable, such as 23/04/2002, the statement will be underlined and an error message will appear in the
Task List window. The description of the error is Date constant is not valid.
The Date data type is extremely flexible; Visual Basic knows how to handle date and time values, so you
won’t have to write complicated code to perform the necessary conversions. To manipulate dates and
times, use the members of the Date type, which are discussed in detail in Chapter “Handling Strings,
Characters, and Dates”, or the date and time functions of VB 6, which are still supported by VB 2008.
You can also perform arithmetic operations with date values. VB recognizes your intention to subtract dates
and it properly evaluates their difference. The result is a TimeSpan object, which represents a time interval.
If you execute the following statements, the value 638.08:49:51.4970000 will appear in the Output window:
! Single distance!
Symbol Data Type Example
# Double ExactDistance
@ Decimal Balance@
Using type identifiers doesn’t help to produce the cleanest and easiest-to-read code. They’re relics from
really old versions of BASIC, and if you haven’t used them in the past, there’s no really good reason to start
using them now.
Converting Variable Types
In many situations, you will need to convert variables from one type into another. Table 2.4 shows
the methods of the Convert class that perform data-type conversions.
In addition to the methods of the Convert class, you can still use the data-conversion functions of
VB (CInt() to convert a numeric value to an Integer, CDbl() to convert a numeric value to a Double,
CSng() to convert a numeric value to a Single, and so on), which you can look up in the
documentation. If you’re writing new applications in VB 2008, use the new Convert class to convert
between data types.
Dim B As Double
B = Convert.ToDouble(A)Code language: VB.NET (vbnet)
Suppose that you have declared two integers, as follows:
ToBoolean Boolean
ToByte Byte
ToDateTime Date
ToDecimal Decimal
ToDouble Double
ToSingle Single
ToString String
Method Converts Its Argument To
If the Strict option is on and you attempt to perform the same assignment, the compiler will
generate an error message to the effect that you can’t convert a Double to an Integer. The exact
message is Option Strict disallows implicit conversions from Double to Integer.
When the Strict option is on, VB 2008 will perform conversions that do not result in loss of accuracy
(precision) or magnitude. These conversions are called widening conversions. When you assign an
Integer value to a Double variable, no accuracy or magnitude is lost. This is a widening conversion,
because it goes from a narrower to a wider type.
On the other hand, when you assign a Double value to an Integer variable, some accuracy is lost
(the decimal digits must be truncated). This is a narrowing conversion, because we go from a data
type that can represent a wider range of values to a data type that can represent a narrower range
of values.
Because you, the programmer, are in control, you might want to give up the accuracy —
presumably, it’s no longer needed. Table 2.5 summarizes the widening conversions that VB 2008
will perform for you automatically.
Single Double
Double None
Char String
If the Strict option is on, the compiler will point out all the statements that may cause runtime errors,
and you can reevaluate your choice of variable types. You can also turn on the Strict option
temporarily to see the compiler’s warnings, and then turn it off again.
User-Defined Data Types
In the previous sections, we used variables to store individual values. As a matter of fact, most
programs store sets of data of different types. For example, a program for balancing your
checkbook must store several pieces of information for each check: the check’s number, amount,
date, and so on. All these pieces of information are necessary to process the checks, and ideally,
they should be stored together.
You can create custom data types that are made up of multiple values using structures. A VB
structure allows you to combine multiple values of the basic data types and handle them as a
whole. For example, each check in a checkbook-balancing application is stored in a separate
structure (or record), as shown in Figure 2.3. When you recall a given check, you need all the
information stored in the structure.
To define a structure in VB 2008, use the Structure statement, which has the following syntax:
Structure structureName
After this declaration, you have in essence created a new data type that you can use in your
application. structureName can be used anywhere you’d use any of the base types (Integers,
Doubles, and so on). You can declare variables of this type and manipulate them as you
manipulate all other variables (with a little extra typing). The declaration for the CheckRecord
structure shown in Figure 2.3 is as follows:
Structure CheckRecord
To declare variables of this new type, use a statement such as this one:
You didn’t write any code for the Equals, GetType, and ToString members, but they’re standard
members of any Structure object, and you can use them in your code. Both the GetType and
ToString methods will return a string like ProjectName.FormName + CheckRecord. You can
provide your own implementation of the ToString method, which will return a more meaningful
string:
check2.CheckNumber = 275
check2.CheckDate = #09/12/2008#
check2.CheckAmount = 104.25
check2.CheckPaidTo = "Gas Co."Code language: VB.NET (vbnet)
You can also create arrays of structures with a declaration such as the following (arrays are
discussed later in this chapter):
Dim Checks(100) As CheckRecordCode language: VB.NET (vbnet)
Each element in this array is a CheckRecord structure and it holds all the fields of a given check.
To access the fields of the third element of the array, use the following notation:
Checks(2).CheckNumber = 275
Checks(2).CheckDate = #09/12/2008#
Checks(2).CheckAmount = 104.25
Checks(2).CheckPaidTo = "Gas Co."Code language: VB.NET (vbnet)
If you want to find out whether an object variable has been initialized, use the Is or IsNot operators,
as shown in the following example:
CBool(expression)
1
Converts the expression to Boolean data type.
CByte(expression)
2
Converts the expression to Byte data type.
CChar(expression)
3
Converts the expression to Char data type.
CDate(expression)
4
Converts the expression to Date data type
CDbl(expression)
5
Converts the expression to Double data type.
CDec(expression)
6
Converts the expression to Decimal data type.
CInt(expression)
7
Converts the expression to Integer data type.
CLng(expression)
8
Converts the expression to Long data type.
CObj(expression)
9
Converts the expression to Object type.
CSByte(expression)
10
Converts the expression to SByte data type.
CShort(expression)
11
Converts the expression to Short data type.
CSng(expression)
12
Converts the expression to Single data type.
CStr(expression)
13
Converts the expression to String data type.
CUInt(expression)
14
Converts the expression to UInt data type.
CULng(expression)
15
Converts the expression to ULng data type.
CUShort(expression)
16
Converts the expression to UShort data type.
Example
The following example demonstrates some of these functions −
Live Demo
Module DataTypes
Sub Main()
Dim n As Integer
Dim da As Date
Dim bl As Boolean = True
n = 1234567
da = Today
Console.WriteLine(bl)
Console.WriteLine(CSByte(bl))
Console.WriteLine(CStr(bl))
Console.WriteLine(CStr(da))
Console.WriteLine(CChar(CChar(CStr(n))))
Console.WriteLine(CChar(CStr(da)))
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
True
-1
True
12/4/2012
1
1
Forcing Variable Declarations VB Help
Visual Basic doesn’t enforce variable declaration, which is a good thing for the average programmer. When you want to slap
together a “quick-and-dirty” pro-gram, the last thing you need is someone telling You Ito decide which variables you’re going to
use and to declare them before using them.
But most programmers accustomed to the free format of Visual Basic also carry their habits of quick-and-dirty coding to large
projects. When writing large appli-cations, you will probably find that variable declaration is a good thing. It will help you write
clean code and simplify debugging. Variable declaration eliminates the source of the most common and pesky bugs.
If you have gotten spoiled, you can ask Visual Basic to. enforce variable declaration for you. To do so, place the following
statement in the declarations section of ; a Form or Module:
Option Explicit
This statement tells the compiler to check each variable before using it and to issue an error message if you attempt to use a
variable without declaring it. If you omit the Option Explicit statement, Visual Basic creates variables as needed.
The option Explicit statement must be included in every Module in which you want to enforce variable declaration. If you decide
to declare all variables in your projects, you can ask Visual Basic to insert the Option Explicit statement automatically in every
Module by checking the Require Variable Declaration checkbox in the Options dialog box (choose Tools> Options), as shown in
Figure 3.2.
FIGURE 3.2
Let’s examine the side effects of implicit variable declaration in your application. You could use the following statements to
convert German marks to U.s. dollars:
DM2USD =1.562
USDollars = amount * DM2USD
The first time your code refers to the DM2USD variable name, Visual Basic creates a new variable and then uses it as if it was
declared.
Suppose the variable DM2USD appears in many places in your application. If. in one of these places you type DM2USD instead
of DM2USD and the program doesn’t enforce variable declaration, the compiler will create a new variable, assign it the value
zero, and then use it. Any amount converted with the DM2UDS variable will be zero! If the application enforces variable
declaration, the compiler will complain (the DM2UDS variable hasn’t been declared), and you will catch the error.
Many programmers, though, feel restricted by having to declare variables. Others live by it. Depending on your experiences with
Visual Basic, you can decide for yourself. For a small application, you don’t have to declare variables. It’s too much typing. But
for large applications that may take weeks or months to develop, you should consider variable declaration.
A Variable’s Scope
In addition to its type, a variable also has a scope. The scope of a variable is the section of the application that can see and
manipulate the variable. If a variable is declared within a procedure, only the code in the specific procedure has access to that
variable. This variable doesn’t exist for the rest of the application. When the. variable’s scope is limited to a procedure it’s
called local.
Suppose you’re coding the Click event of a Common button to calculate the sum of all even numbers in the range 0 to 100. One
possibility is the following:
The variables i and Sum are local to the CommandClick() procedure. If you attempt to set the value of the Sum variable from
within another procedure, Visual Basic will create another Sum’variable and use it. But this won’t affect the variable Sum in the
Command_Click() subroutine.
Sometimes, however, you’ll need to use a variable with a broader scope, such as one whose value is available to
all procedures within the same Form or Module. These variables are called Form-wide (or Module-wide) and can be
accessed from within all procedures in a component. In principle; you could declare all variables in the Form’s declaration
section, but this would lead to problems. Every procedure in the Form would have access to the variable, and you would’ need to
be careful not to change the value of a variable without good reason. Variables that are needed by a single procedure (such as
loop counters, for example), should be declared in the procedure that uses them, not as Form variables.
Finally, in some situations the entire application must access a certain variable. In this case, the variable must be declared as
Public. Public variables have a global scope they are visible from any part of the application). To declare a public variable, use
the Public statement in place of the Dim statement. Moreover, public variables may not appear inside procedures. They must be
declared as Form variables or in a Module.
The Lifetime of a Variable
In addition to type and scope, variables have a lifetime, which is the period for which they retain their value. Variables declared
as Public exist for the lifetime the application. Local variables, declared within procedures with the Dim or Private statement, live
as long as the procedure. When the procedure finishes, the local variables cease to exist and the allocated memory is returned to
the system. Of course, the same procedure can be called again” In this case, the local variables are recreated and initialized
again.
You also can force a local variable to preserve its value between procedure calls with the Static keyword. Suppose the user of
your application can enter numeric values at any time. One of the tasks performed by the application is to track the average of
the numeric values. Instead of adding all the values each time the user adds it new value and dividing by the count, you can keep
a running total with the function RunningAvg(), which is shown next.
You must declare the variables CurrentTotal and TotalItems outside the function so that their values are preserved between calls.
Alternatively, you can declare them in the function with the Static keyword:
The advantage of using static variables is that they help you minimize the number of total variables in the application. All you
need is the running average.which the RunningAvg() function provides without making its variables visible to the re~t of the
application. Therefore, you don’t risk changing the variables’ values
from within other procedures.
Variables declared in a Form outside any procedure take effect when the Form is loaded and cease to exist when the Form is
unloaded. If the Form is loaded again, its variables are initialized, as if it’s being loaded for the first time ..
Constants
. .. ,
Some variables don’t change value during the execution of a program. These are constants that appear many times in your code.
For instance, if your program does math calculations, the value of pi (3.14159… ) may appear many times in your code. These
values are best represented by constants. Instead of typing the value 3.14159 over and over again, you can define a constant,
name it pi, and use the name of the constant in your code. The following statement:
Area = 2 * pi * Radius
is much easier to understand· than the equivalent:
Area = 2 * 3.14159 * Radius
You could declare pi as a variable, but constants are preferred for two reasons:
1. Constants don’t change value. This is a safety feature. Once a constant has been declared, you can’t change its value in
subsequent statements, therefore,you can be sure that the value specified in the constant’s declaration will take effect in the
entire program.
2. Constants are processed faster than variables. When the program is running, the values of constants don’t have to be looked up.
The compiler substitutes constant names with their values, and the program executes faster.
The manner in which you declare constants is similar to the manner in which . you declare variables, except that in addition to
supplying the constant’s name you must also supply a value, as follows:
Canst constantname [As type] = value
The As type part of the declaration is optional. If you omit it, the constant’s type is determined by the value you assign to it.
Constants also have a scope and can be Public or Private. The constant pi, for instance, is usually declared in a Module
as Public so that every procedure can access it:
Public Const pi AS Double = 3.14159265358979
The constantname variable is a valid constant name that follows the same rules as variable names. The constant’s value is a
literal value or a simple expression composed of numeric or string constants and operators. You can’t use functions in declaring
variables. One way to define the value of pi is as follows:
pi = 4 * Atn(1)
However, you can’t use this assignment in the constant declaration. You must supply the actual value.
constant van be strings too, much as
Const ExpDate = ’31/12/1997
or:
Const ValidKey = ‘A567dfe’
Visual Basic uses constants extensively to define the various arguments of its methods and the settings of the various control
properties. The value of a Check-Box control, for instance, can be 0 (unchecked), 1(checked), or 2 (grayed). Instead of using
statements like:
Checkl.Value = 0
Check2.Value = 2
use the built-in constants vbUnchecked and vbGrayed:
Checkl.Value – vbUnchecked
Check2.Value – vbGrayed
Visual Basic’s constants are prefixed with vb, indicating that they are Visual Basic constants. The constants vbUnchecked and
vbGrayed are built into the language, and you don’t need to declare them. Their symbolic names make the code much easier to
read and maintain. Avoid the vb prefix when declaring your own constants. Other components of the language use different
prefixes. For example, the Database Access Objects use constants with the prefix.
Constant declarations may include other constants. In math calculations, the value pi is as common as the value 2. * pi. You can
declare these two values as constant:
Public Const pi As Double – 3.141592653SJ979
Public Canst pi2 As Double – 2 * pi
You can also create circular constant defination, such as the following:
Const constant1 = constant * 2
Const constant2 = constant 1/ 2
This circular definition doesn’t lead an, where (none of the constants has a value) and should be avoided.
It’s very unlikely that these two declaration will appear in the same Module, but you may forget how you defined constant1; in
one of the Modules and attempt to define constant2 in terms of constant1 in a not her Module. If this happens, Visual Basic
generates a runtime error. If you declare all your constants in a single Module, they’re easier to maintain and chance.
forcing variable declaration in vb.net
Option Explicit statement ensures whether the compiler requires all variables to be explicitly declared or not
before it use in the program.
Option Explicit [On Off]
The Option Explicit has two modes. On and Off mode. If Option Explicit mode in ON , you have to declare all
the variable before you use it in the program . If not , it will generate a compile-time error whenever a variable
that has not been declared is encountered .If the Option Explicit mode is OFF , Vb.Net automatically create a
variable whenever it sees a variable without proper declaration.
With the Option Explicit On , you can reduce the possible errors that result from misspelled variable names.
Because in Option Explicit On mode you have to declare each variable in the program for storing data.
Take a look at the following programs, it will give you a clear picture of Option Explicit.
The following program is a normal vb.net program , so the default mode of Option Explicit On is using. The
default is Option Explicit On , so we do not need to put it in the source code.
VB.NET Source Code
End Class
VB.NET Operators
In VB.NET programming, the Operator is a symbol that is used to perform various operations on
variables. VB.NET has different types of Operators that help in performing logical and mathematical operations on
data values. The Operator precedence is used to determine the execution order of different Operators in the VB.NET
programming language.
3+2-1
The symbol + and - are the Operators, and the 3, 2, and 1 are operands.
o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators
o Bit Shift Operators
o Assignment Operators
o Concatenation Operators
o Miscellaneous Operators
Arithmetic Operators
The Arithmetic Operators in VB.NET, used to perform mathematical operations such as subtraction, addition,
multiplication, division, etc. on the operands in VB.NET. These are as follows:
Arithmetic_Operator.vb
Imports System
Module Arithmetic_Operator
Sub Main()
'Declare a, b And c as integer Data Type()
Dim a, b, c As Integer
Dim d As Single
a = 17
b=4
' Use of + Operator
c=a+b
Console.WriteLine(" Sum of a + b is {0}", c)
'Use of - Operator
c=a-b
Console.WriteLine(" Subtraction of a - b is {0}", c)
'Use of * Operator
c=a*b
Console.WriteLine(" Multiplication of a * b is {0}", c)
'Use of / Operator
d=a/b
Console.WriteLine(" Division of a / b is {0}", d)
'Use of \ Operator
c=a\b
Console.WriteLine(" Similar to division Operator (return only integer value) of a - b is {0}", c)
'Use of ^ Operator
c=a^b
Console.WriteLine(" Power of a ^ b is {0}", c)
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
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 Non-Equality Operator that checks whether the value of (A <> B), check Non-
the two operands is not equal; it returns true; otherwise, it Equality
shows false.
> A greater than symbol or Operator is used to determine (A > B); if yes, TRUE,
whether the value of the left operand is greater than the
value of the right operand; If the condition is true, it returns Else FALSE
TRUE; otherwise, it shows FALSE value.
< It is a less than symbol which checks whether the value of the (A < B); if the condition is
left operand is less than the value of the right operand; If the true, returns TRUE else
condition is true, it returns TRUE; otherwise, it shows FALSE FALSE
value.
<= This symbol represents less than equal to which determines A <= B
the first operand is less than or equal to the second operand,
and if the condition is true, it returns TRUE; otherwise, it
shows FALSE.
Is The Is Operator is used to validate whether the two objects result = obj1 Is obj2
reference the same variable or object; If the test is true, it
returns True; otherwise, the result is False. In short, it checks
the equality of the objects. An Is Operator is also used to
determine whether the object refers to a valid object.
IsNot The IsNot Operator is similar to Is Operator, except that the Result = obj1 IsNot obj2
two object references the different object; if yes, the result is
True; otherwise, the result is False.
Like The Like Operator is used to check the pattern expression of result = string Like the
string variable; And if the pattern matched, the result is True; pattern, the pattern
otherwise, it returns False. represents the series of
characters used by Like
Operator.
Comparison_Operator.vb
Imports System
Module Comparison_Operator
Sub Main()
'declaration of Integer, Object and String Data Type variables
Dim x As Integer = 5
Dim y As Integer = 10
Dim Result, obj, obj2 As Object
Dim str, str2 As String
str = "Apple12345"
str2 = "Apple12345"
obj = 10
obj2 = 20
'Use of = Operator
Console.WriteLine(" Output of x = y is {0}", x = y)
'Use of Is Operator
Result = obj Is obj2
Console.WriteLine(" Output of obj Is obj2 is {0}", Result)
'Use of Is Operator
Result = obj IsNot obj2
Console.WriteLine(" Output of obj IsNot obj2 is {0}", Result)
Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:
Logical and Bitwise Operators
The logical and bitwise Operators work with Boolean (true or false) conditions, and if the conditions become true, it
returns a Boolean value. The following are the logical and bitwise Operators used to perform the various logical
operations such as And, Or, Not, etc. on the operands (variables). Suppose there are two operand A and B, where A is
True, and B is False.
And The And Operator represents, whether both the operands are true; the (A And B),
result is True. result = False
Or It is an Or Operator that returns a true value; if anyone operand is true (A Or B), result
from both the operands. = True
Not The Not Operator is used to reverse the logical condition. For example, Not A
if the operand's logic is True, it reveres the condition and makes it False.
Or
Not(A And B) is
True
Xor It is an Exclusive OR Operator that represents, whether both the A Xor B is True
expression is true or false, the result is True; otherwise, the result is
False.
AndAlso It is a logical AND Operator that performs short-circuit operation on the A AndAlso B =
variables, and if both the operands are true, the result is True else the False
result is False.
Logic_Bitwise.vb
Imports System
Module Logic_Bitwise
Sub Main()
Dim A As Boolean = True
Dim B As Boolean = False
Dim c, d As Integer
c = 10
d = 20
'Use of Or Operator
If A Or B Then
Console.WriteLine(" Operands A Or B are True")
End If
'Use of Or Operator
If c Or d Then
Console.WriteLine(" Operands c Or d is True")
End If
Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:
Operator Description
AND The Binary AND Operator are used to copy the common binary bit in the result if the bit
exists in both operands.
OR The Binary OR Operator is used to copy a common binary bit in the result if the bit found
in either operand.
XOR The Binary XOR Operator in VB.NET, used to determine whether a bit is available to copy in
one operand instead of both.
Not The binary NOT Operator is also known as the binary Ones' Compliment Operator, which is
used to flip binary bits. This means it converts the bits 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
Imports System
Module Bitshift_Operator
Sub Main()
Dim x, y, z As Integer
x = 12
y = 25
Dim a, b As Double
a = 5 ' a = 5(00000101)
b = 9 ' b = 9(00001001)
'Use of Or Operator
z = x Or y
Console.WriteLine(" BitShift Operator x Or y is {0}", z)
z = x Xor y
Console.WriteLine(" BitShift Operator x Xor y is {0}", z)
z = Not y
Console.WriteLine(" BitShift Operator Not y is {0}", z)
'Output is 00010010
Console.WriteLine(" Bitwise Left Shift Operator - b<<1 = {0}", b << 1)
'Output is 00000100
Console.WriteLine(" Bitwise Right Shift Operator - b>>1 = {0}", a << 1)
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.
+= An Add AND assignment Operator is used to add the value X += 5, which means
of the right operand to the left operand. And the result is X= X+5 ( 5 will add and
assigned to the left operand. assign to X and then result
saved to Left X operand)
&= It is a concatenate string assignment Operator used to bind Str &= name, which is same
the right-hand string or variable with the left-hand string or as Str = Str & name
variable. And then, the result will be assigned to the left
operand.
Assign_Operator.vb
Imports System
Module Assign_Operator
Sub Main()
'Declare variable and b As Integer
Dim A As Integer = 5
Dim B As Integer
Dim Str, name As String
name = "come"
Str = "Wel"
'Use of = Operator
B=A
Console.WriteLine(" Assign value A to B is {0}", B)
'Use of += Operator
B += A
Console.WriteLine(" Output of B += A is {0}", B)
'Use of -= Operator
B -= A
Console.WriteLine(" Output of B -= A is {0}", B)
'Use of *= Operator
B *= A
Console.WriteLine(" Output of B *= A is {0}", B)
'Use of /= Operator
B /= A
Console.WriteLine(" Output of B /= A is {0}", B)
'Use of = Operator
B \= A
Console.WriteLine(" Output of B \= A is {0}", B)
'Use of ^= Operator
B ^= A
Console.WriteLine(" Output of B ^= A is {0}", B)
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:
& It is an ampersand symbol that is used to bind two or more operand Result = Wel
together. Furthermore, a nonstring operand can also be concatenated & come,
with a string variable ( but in that case, Option Strict is on). Result =
Welcome
MyProgram.vb
Imports System
Module MyProgram
Sub Main()
Dim str As String = "Wel"
Dim str2 As String = "come"
Dim str3 As String = " "
Dim str4 As String = "to JavatPoint"
Dim result As String
Dim result2 As String
result = str & str2
Console.WriteLine(" Result = str & str2 gives = {0}", result)
result2 = str + str2 + str3 + str4
Console.WriteLine(" Result = str + str2 + str3 +str4 gives = {0}", result2.ToString)
Console.ReadLine()
End Sub
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
Function It defines the lambda expression, which Dim mul2 = Function(num As Integer) num
Expression declares the parameter and code. A * 4
Lambda expression is a function that is Console.WriteLine(mul2(4))
used to calculate and return value without
defining the name.
Misc_Operator.vb
Imports System
Module Misc_Operator
Sub Main()
' Initialize a variable
Dim a As Integer = 50
' GetType of the Defined Type
Console.WriteLine(GetType(Double).ToString())
Console.WriteLine(GetType(Integer).ToString())
Console.WriteLine(GetType(String).ToString())
Console.WriteLine(GetType(Single).ToString())
Console.WriteLine(GetType(Decimal).ToString())
'Use of Function()
Dim multiplywith10 = Function(sum As Integer) sum * 10
Console.WriteLine(multiplywith10(10))
Console.WriteLine(If(a >= 0, "Negative", "Positive"))
End Sub
End Module
Now compile and execute the above code by pressing the F5 button or Start button in Visual studio, it returns the
following output:
VB.NET Control Statements
In VB.NET, the control statements are the statements that controls the execution of the program on the
basis of the specified condition. It is useful for determining whether a condition is true or not. If the
condition is true, a single or block of statement is executed. In the control statement, we will use if- Then, if
Then Else, if Then ElseIf and the Select case statement.
We can define more than one condition to be evaluated by the program with statements. If the defined
condition is true, the statement or block executes according to the condition, and if the condition is false,
another statement is executed.
The following figure shows a common format of the decision control statements to validate and execute a
statement:
The above diagram shows that if the defined condition is true, statement_1 will be executed, and if the
condition is false, statement_2 will be executed.
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:
If condition Then
[Statement or block of Statement]
End If
In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and the statement can
be single or group of statements that will be executed when the condition is true.
Module1.vb
Module Module1
' Declaration of variable str
Dim str As String = "JavaTpoint"
Sub Main()
' if str equal to "JavaTpoint", below Statement will be executed.
If str = "JavaTpoint" Then
Console.WriteLine("Welcome to the JavaTpoint")
End If
Console.WritLine("press any key to exit?")
Console.ReadKey()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
As we can see in the above example, if the value of str is equal to JavaTpoint, the condition is true, and it
prints the Statement.
Example 2: Write a program to print a number is greater than another number in VB.NET.
if_statment2.vb
Module if_statement2
Sub Main()
?Definition of variables
Dim no1, no2 As Integer
Console.WriteLine("Enter any two number:")
no1 = Console.ReadLine() ?read no1 from user
no2 = Console.ReadLine() ?read no2 from user
If no1 > no2 Then
Console.WriteLine("First number is greater than second number")
End If
If no1 < no2 Then
Console.WriteLine("Second number is greater than First number")
End If
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub
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:
If (Boolean_expression) Then
'This statement will execute if the Boolean condition is true
Else
'Optional statement will execute if the Boolean condition is false
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
Module If_Else_statement
Sub Main()
Dim num As Integer
Console.WriteLine("Enter the Number")
num = Console.ReadLine() 'read data from console
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
Module if_else_statement2
Sub Main()
Dim a As Integer
Dim b As Integer
Console.WriteLine("Enter the first number : ")
a = Console.ReadLine()
If a > b Then
Console.WriteLine(" larger number = {0} and smaller number = {1} ", a, b)
Else
Console.WriteLine(" larger number = {0} and smaller number = {1} ", b, a)
End If
Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
VB.NET If-Then-ElseIf statement
The If-Then-ElseIf Statement provides a choice to execute only one condition or statement from multiple
statements. Execution starts from the top to bottom, and it checked for each If condition. And if the
condition is met, the block of If the statement is executed. And if none of the conditions are true, the
last block is executed. Following is the syntax of If-Then-ElseIf Statement in VB.NET as follows:
Syntax
If(condition 1)Then
' Executes when condition 1 is true
ElseIf( condition 2)Then
' Executes when condition 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the condition 3 is true
Else
' executes the default statement when none of the above conditions is true.
End If
Flowchart
The following diagram represents the functioning of the If-Else-If Statement in the VB.NET programming
language.
If this condition is true in the flowchart of the if-else-if statement, the statement is executed within the if
block. If the condition is not true, it passes control to the next ElseIf condition to check whether the
condition is matched. And if none of the conditions are matched, the else block is executed.
if_elseIf.vb
Module if_elseIf
Sub Main()
Dim var1 As Integer
Console.WriteLine(" Input the value of var1: ")
var1 = Console.ReadLine()
If var1 = 20 Then
'if condition is true then print the following statement'
Console.WriteLine(" Entered value is equal to 20")
ElseIf var1 < 50 Then
Console.WriteLine(" Entered value is less than 50")
Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
Example 2: Write a program to use the If-Then-ElseIf Statement for calculating the division obtained by the
student. Also, take the marks obtained by the student in 5 different subjects from the keyboard.
if_elseIf2.vb
Module If_elseIf2
Sub Main() ' execution start from Main() method
Dim m1, m2, m3, m4, m5, per As Integer
Console.WriteLine("Enter marks in five subjects ")
' Read the marks of five subject
m1 = Console.ReadLine()
m2 = Console.ReadLine()
m3 = Console.ReadLine()
m4 = Console.ReadLine()
m5 = Console.ReadLine()
per = (m1 + m2 + m3 + m4 + m5) / 5
If (per >= 70) Then
'if condition is true, print the first division
Console.WriteLine(" First division")
ElseIf (per >= 60) Then
'if ElseIf condition is true, print the second division
Console.WriteLine(" Second division")
ElseIf (per >= 50) Then
'if ElseIf condition is true, print the third division
Console.WriteLine(" Third division")
ElseIf (per >= 40) Then
'if ElseIf condition is true, print only pass with grace
Console.WriteLine(" Only Pass with Grace")
Else
'if none of the condition is true, print the Failed
Console.WriteLine(" Failed")
End If
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub
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
Case value2 'defines the item or value that you want to match.
// Define a statement to execute
Case Else
// Define the default statement if none of the conditions is true.
End Select
Furthermore, you can also set more than one condition in a single case statement, such as:
Case Else
// define the default statement if none of the condition is true
End Select
The following flowchart represents the functioning of the Select case statement in the VB.NET programming
language.
In Flowchart, the Select Case statement represents the evaluating of the process start from top to bottom. If
the expression or value is matched with the first select case, statement -1 is executed else the control
transfer to the next case for checking whether the expression is matching or not. Similarly, it checks all Select
case statements for evaluating. If none of the cases are matched, the Else block statement will be executed,
and finally, the Select Case Statement will come to an end.
Example 1: Write a program to display the Days name using the select case statement in VB.NET.
Select_case.vb
Imports System
Module Select_case
Sub Main()
'define a local variable.
Dim Days As String
Days = "Thurs"
Select Case Days
Case "Mon"
Console.WriteLine(" Today is Monday")
Case "Tue"
Console.WriteLine(" Today is Tuesday")
Case "Wed"
Console.WriteLine("Today is Wednesday")
Case "Thurs"
Console.WriteLine("Today is Thursday")
Case "Fri"
Console.WriteLine("Today is Friday")
Case "Sat"
Console.WriteLine("Today is Saturday")
Case "Sun"
Console.WriteLine("Today is Sunday")
Case Else
Console.WriteLine(" You have typed Something wrong")
End Select
Console.WriteLine("You have selected : {0}", Days)
Console.WriteLine("Press any key to exit...")
Console.ReadLine()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
In the select case statement, the value of Days "Thurs" will compare all the available select cases' values in a
program. If a value matched with any condition, it prints the particular statement, and if the value is not
matched with any select case statement, it prints the default message.
Example 2: Write a program to perform an arithmetic operation using the Select case statement in VB.NET.
Operation.vb
Operation.vb
Imports System
Module Operation
Sub main()
'declaration of the variables
Dim num1, num2, sum As Integer
Dim def As Char
'initialization of num1 and num2 variable
num1 = 2
num2 = 6
Console.WriteLine(" Want to perform any operation?")
Console.WriteLine(" A for Addition")
Console.WriteLine(" S for Subtraction")
Console.WriteLine(" M for Multiplication")
Console.WriteLine(" D for Division")
Console.WriteLine(" Please enter any input")
def = Console.ReadLine()
Select Case def
Case "A"
'perform Addition
sum = num1 + num2
Console.WriteLine(" Addition of two number is :{0}", sum)
Case "S"
'perform Subtraction
sum = num2 - num1
Console.WriteLine(" Subtraction of two number is :{0}", sum)
Case "M"
'perform Multiplication
sum = num1 * num2
Console.WriteLine(" Multiplication of two number is :{0}", sum)
Case "D"
'Peform Division
sum = num2 / num1
Console.WriteLine(" Division of two number is :{0}", sum)
Case Else
'If none of the operation matched, call default statement
Console.WriteLine(" Please enter only define operation With Capital letter")
End Select
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
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
Module Module1
Sub Main()
Case 10
Console.WriteLine("X Value: 10")
Select Case y
Case 5
Console.WriteLine("Nested Switch Value: 5")
Select Case y - 2
Case 3
Console.WriteLine("Another Nested Switch Value: 3")
End Select
End Select
Case 15
Console.WriteLine("X Value: 15")
Case 20
Console.WriteLine("X Value: 20")
Case Else
Console.WriteLine("Not Known")
End Select
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the following
output:
Example 2: Write a program to use the nested select case statement in VB.NET.
nested_selectcase.vb
Imports System
Module nested_selectcase
Sub Main()
Dim num As Integer
Dim str As String
str = "F"
str = Console.ReadLine()
Select Case str
Case "A", "a"
Console.WriteLine(" This is a VB.NET Tutorial")
Case "B", "b"
Console.WriteLine(" Welcome to the JavaTpoint")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case 2
Console.WriteLine(" You are in block 2")
Console.WriteLine("Only First two letter such as C and D")
str = Console.ReadLine()
Select Case str
Case "C", "c"
Console.WriteLine(" Welcome to the World!")
Case "D", "d"
Console.WriteLine(" Want to go in Heaven")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case 3
Console.WriteLine(" You are in block 3")
Console.WriteLine("Only First two letter such as E and F")
str = Console.ReadLine()
Select Case str
Case "E", "e"
Console.WriteLine(" VB.NET is a programming language to develop web, window, and console-
based application. ")
Case "F", "f"
Console.WriteLine(" You have to basic knowledge of c and c++")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case Else
Console.WriteLine(" Something is wrong")
End Select
Console.ReadLine()
End Sub
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 have only defined the first three numbers 1-3 and if the number matches to any
case statement, the select statement is executed. Here, we have entered 2 that is matched with case 2 and it
executes a block as shown above. And this block executes the statement "Only the First two letters such as C
and D". Therefore, we enter a letter D, letter D is matched with the nested select case statement, and if a
match is found, it executes the select case statement as shown above.
Visual Basic – Messages and data input/output
Introduction
One way for a user to communicate with a procedure is via a dialogue box. The easiest
way to do this in VB is to use one of the pre-defined ones. VB has two kinds, a Message
box and an Input box.
Message box
The MsgBox function displays a message, waits for the user to click a button and returns
a value indicating which button has been chosen. The simplest MsgBox contains only a
message string and an OK button. The general syntax is
MsgBox(prompt [,buttons] [,title]),
where the quantities within [] are optional arguments, with
prompt: string expression displayed in the message (max length 1024 characters)
buttons: numerical expression that is sum of values specifying the type of buttons
to display,
title: string expression displayed in the title bar.
Some of the button values are given below. (For a full list see the Help file).
Value Constant Display
0 vbOKOnly OK button only
1 vbOKCancel OK and Cancel buttons
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
32 vbQuestion Query icon
48 vbExclamation Warning message icon
0 vbDefaultButton1 First button is default
256 vbDefaultButton2 Second button is default
512 vbDefaultButton3 Third button is default
The value returned by the MsgBox function depends on the button pressed. Some values
are listed below.
Button selected Value Constant
OK 1 vbOK
Cancel 2 vbCancel
Yes 6 vbYes
No 7 vbNo
The MsgBox function can be used as a simple debug tool. To display the contents of
variable variDisplay then use
MsgBox “Contents of variDisplay “ & variDisplay
which creates a message made from concatenating the text Contents of
variDisplay with the data in the variable variDisplay.
1
The example below displays a message box with two buttons, Yes and No, with No as the
default response. The value returned by the MsgBox function depends on the button
pressed by the user.
msg = “Do you want to continue?”
boxButtons = vbYesNo + vbDefaultButton2
msgTitle = “Processing mode”
response = MsgBox(msg, boxButtons, msgTitle)
If response = vbYes Then
msg = “clicked YES”
Else
msg = “Clicked No or pressed ENTER”
End If
MsgBox msg
The previous technique presupposes that the values of the data are know in advance and
have been entered into the spreadsheet BEFORE the procedure is run. The InputBox
function creates and displays a simple dialogue box that contains a prompt, an edit box,
and OK and Cancel buttons. You use this box to allow the user to input data at run-time.
The format of the InputBox function is
InputBox(Prompt, [,title] [,default] [,xpos] [,ypos])
with
prompt := a string expression displayed in the box,
Optional arguments
title:= a string expression displayed in the dialogue box’s title bar. If
omitted nothing is displayed.
default:= default response if no input provided
xpos, ypos specify the horizontal and vertical position of the box. If omitted
the box is centred horizontally and about one-third of the way
down the screen.
A simple example is
radius = InputBox(“Enter radius of circle”, “Circle _
radius”)
2
which will display a dialogue box with a title “Circle radius” and a message “Enter radius
of circle” and wait for the user to enter a value.
The InputBox Method (of the Application object) works like the InputBox function but
the method also allows you specify the data type. This enable you to enter a range, e.g.
A1:A10. If data entered is of the wrong type Excel displays an error message. The
format to use is
Application.InputBox(prompt,title,default,left,top,type)
The arguments, prompt, title and default are as for the InputBox function. The
arguments, left, top, and type are optional, (left and top specify the horizontal and
vertical postion from the top left of the screen in point units (=1/72.27 inch)), type
specifies the data type. If type is omitted the method returns text). Type has the
following values,
Value Description
0 a formula
1 a number
2 text (string)
4 logical
8 cell reference ( a range)
16 error value
64 an array of values
Note, type = 1 + 2 accepts text or number.
The code below asks the user to specify a range to search and a search value. The search
range must be a valid range, e.g. sheet!A1:A10, and the search value is a number.
Sub CountEntries()
Dim allCount As Integer, rangeToSearch As Object
Dim searchValue, c
cellCount = 0
Set rangeToSearch = Application.InputBox( _
Prompt: = “Enter range to search”, _
Type: = 8)
‘ type 8 means entry must be a range object
searchValue = Application.InputBox( _
Prompt: = “Search for value”, _
Type: = 1)
‘ type 1 means a number
If searchValue = False Then Exit Sub
‘ user clicked Cancel
For Each c In rangeToSearch
If c.Value = searchValue Then
cellCount = cellCount + 1
End If
Next c
MsgBox “Number of occurrences of “ & searchValue _
& “ is “ & cellCount
End Sub
3
VBA MsgBox
The MsgBox is a dialog box in the excel VBA that can be used to inform the users of your program.
It displays a pop-up style message box and waits for the user to click a button, and then an action is
performed based on the clicked button by the user.
It provides a way for the end-users to interact with a workbook. It can be a simple alert to the users, or it can
be complicated that needs an action to proceed by the users.
Syntax
Prompt: (required parameter) it refers to a text that is displayed as a message in the dialog box. The
maximum length of the posted message can be 1024 approximately. If the word crosses the defined range,
then the message will be divided using the carriage return character (Chr(13)) or a linefeed character
(Chr(10)) between each line.
Buttons: (optional parameter) it denotes a numeric expression to display the types of buttons, to use the
icon style, the identity of the default button, and the modality of the message box. The default value for
buttons is zero if the left side of the button is blank.
Title: (optional parameter) the title bar of the dialog box displayed the string expression. If the left side of
the dialog box is blank, then the application name is placed in the title bar.
Helpfile: A string parameter that identifies the help file to use for providing context-sensitive help for the
dialog box.
Context: The help author assigns the Help context number to an appropriate topic. If the context is
provided, then the help file must also be provided.
We can configure the message box in many ways with the help of the button parameters. That shows in the
below table, such as:
vbSystemModal 4096 All applications are suspended until the user responds to
the message box
The above values are divided into four groups as the first group of values (0-5) describes the number and
type of buttons displayed in the dialog box. The second group of values (16, 32, 48, and 64) illustrates the
icon style. The third group of values (0, 256, and 512) determines which button is the default. And the
modality of the message box is defined in the fourth group (0, 4096). We can add only one number from
each group to create a final value for the buttons argument.
Return Values
The MsgBox function returns any one value from the following values, which is used to identify the button.
And the only thing that the user has to do that clicked in the message box.
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
Examples
Suppose we want to display a message box with Yes, No, and Cancel buttons, as shown in the below code:
Executes the above function by clicking on the run button on the VBA window. It displays a "Welcome"
message box within a message box and an "OK" button.
After clicking the OK button, another dialog box is displayed with a message "do you like the red color"
and "yes", "no", and "cancel" buttons.
After clicking any button (e.g., yes), the value of that button is stored as an integer. And it displayed a pop-
up message box to the user, as shown below. Using this value, we can understand which button was clicked
by the user.
Introduction
A message box is a special dialog box used to display a piece of information to the user. As opposed to a
regular form, the user cannot type anything in the dialog box. To support message boxes, the Visual Basic
language provides a function named MsgBox. To support message boxes, the .NET Framework provides a
class named.
To display a simple message box, you can use the MsgBox() function with the following formula:
MsgBox(Message)
If the message is made of different sections, you can concatenate them using the & operator. You can also first declare a Str
variable, initialize it, and pass it to the function.
To create a message box using the .NET Framework, you can call the Show() method of the MessageBox class using the
following formula:
MessageBox.Show(Message)
As done for the MsgBox() function, pass a string to the method. Here is an example:
https://demoslotsgames.com/en/ showcases a vivid and colorful world where fruits and candies blend harmoniously with
rewarding bonus rounds. It's not only about fun; it's also a learning experience for those curious about the game mechanics.
In our lessons, we will mostly use the MsgBox() function, not because it is better than the MessageBox class. It is simply a
preference; but it is also because these lessons are for Microsoft Visual Basic, so we give preference to its own (rich) library
Besides displaying a message, a message box can be used to let the user make a decision by clicking a button and, dependin
the button the user would have clicked, the message box would return a value. To be able to return a value, the MsgBox()
function is declared as follows:
If you create a simple message box by providing only the message, it would appear with only one button labeled OK. If you
the user to be able to make a decision and communicate it to you, provide a second argument. The second argument must be
based on the MsgBoxStyle enumeration. When it comes to buttons, some members of this enumeration are:
Integral
To Display MsgBoxStyle
Value
OKOnly 0
OKCancel 1
AbortRetryIgnore 2
YesNoCancel 3
YesNo 4
RetryCancel 5
To use any of these combinations of buttons, call the MessageBoxStyle enumeration and access the desired combination. H
an example:
If you create a simple message box by providing only the message, the dialog box would appear with the name of the projec
the title. To allow you to specify a caption of your choice, provide a second string as the third argument to
the MsgBox() function. Here is an example:
To enhance the appearance of a message box, you can display an icon on it. To support icons, the MsgBoxStyle enumeratio
provides the following additional members:
Integral
To Display MsgBoxStyle
Value
Critical 16
Question 32
Exclamation 48
Information 64
To apply one of these buttons, combine its style with that of the button, using the OR operator. Here is an example:
Here is an example:
A text can be return in the text box by using the InputBox function if the user clicks on
the OK or Enter button. And if the user clicks on the Cancel button, then the InputBox function will return an
empty string (" ").
InputBox function needs proper error handling. If the user clicks the cancel button without entering any
value, then it displayed an error.
Syntax
1. InputBox(prompt[,title][,default][,xpos][,ypos][,helpfile,context])
o Prompt (required parameter): This parameter represents a string, and it is used to display as a
message in the dialog box. The minimum length of prompt is 1024 characters approximately. If the
length of the text is increased, then break the text by using a linefeed character (Chr(10)) or carriage
return character (Chr(13)) between each line of the text.
o Title (optional parameter): The title is a string expression. It is used to display the string in the title bar
of the dialog box. And the application name is placed in the title bar if the left side of the title is
empty.
o Default (optional parameter): It takes the text as a default parameter in the textbox to display it to the
users.
o XPos (optional parameter): The position of the X-axis is used to show the prompt distance from the
left side of the screen as horizontally. The input box is centered horizontally if its value is null.
o YPos (optional parameter): The position of the Y-axis is used to show the prompt distance from the
left side of the screen as vertically. , then the input box is centered vertically If its value is blank.
o Helpfile (optional parameter): The helpfile is a string expression. This parameter is used to identify the
help file that provides context-sensitive help to the dialog box.
o Context (optional parameter): It is a numeric expression that is used to identify the Help context
number. This number is assigned to a suitable help topic by the Help author. The helpfile must be
present if we want to provide the context.
Step 3: Write the word "InputBox", and we will see the syntax of the InputBox.
Step 4: Now give the Prompt as "Your Name", title as "personal information", and Default as "Enter Here".
Example
We use the popular features of an InputBox function shown in the following example, such as:
o This code asks for the input with the help of an InputBox and assigns it to a variable.
o It verifies the code; otherwise, it exists.
Now run the above code using the Run button, and we will get the result in a message box, such as:
While the dialog box is displayed, then the user has to press one of the buttons.
When the user presses any one button from the displayed buttons, then a text string is return with the help
of the InputBox function.
o If the user clicks on the OK button, then the text string has been entered into the dialog box.
o If the user clicks on the Cancel button, then an empty text string is returned.
In the above example, the returned text string is assigned to the MyInput variable before the execution of
the code.
VB.Net - PrintDialog Control
The PrintDialog control lets the user to print documents by selecting a printer and choosing which
sections of the document to print from a Windows Forms application.
There are various other controls related to printing of documents. Let us have a brief look at these
controls and their purpose. These other controls are −
The PrintDocument control − it provides support for actual events and operations of
printing in Visual Basic and sets the properties for printing.
The PrinterSettings control − it is used to configure how a document is printed by specifying
the printer.
The PageSetUpDialog control − it allows the user to specify page-related print settings
including page orientation, paper size and margin size.
The PrintPreviewControl control − it represents the raw preview part of print previewing
from a Windows Forms application, without any dialog boxes or buttons.
The PrintPreviewDialog control − it represents a dialog box form that contains a
PrintPreviewControl for printing from a Windows Forms application.
AllowCurrentPage
1 Gets or sets a value indicating whether the Current
Page option button is displayed.
AllowPrintToFile
2 Gets or sets a value indicating whether the Print to file check
box is enabled.
AllowSelection
3 Gets or sets a value indicating whether the Selection option
button is enabled.
AllowSomePages
4 Gets or sets a value indicating whether the Pages option
button is enabled.
Document
5 Gets or sets a value indicating the PrintDocument used to
obtain PrinterSettings.
PrinterSettings
6
Gets or sets the printer settings the dialog box modifies.
PrintToFile
7 Gets or sets a value indicating whether the Print to file check
box is selected.
ShowHelp
8 Gets or sets a value indicating whether the Help button is
displayed.
ShowNetwork
9 Gets or sets a value indicating whether the Network button
is displayed.
Reset
1
Resets all options to their default values.
RunDialog
2 When overridden in a derived class, specifies a common
dialog box.
ShowDialog
3
Runs a common dialog box with a default owner.
Example
In this example, let us see how to show a Print dialog box in a form. Take the following steps −
Add a PrintDocument control, a PrintDialog control and a Button control on the form. The
PrintDocument and the PrintDialog controls are found on the Print category of the controls
toolbox.
Change the text of the button to 'Print'.
Double-click the Print button and modify the code of the Click event as shown −
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintDialog1.Document = PrintDocument1
PrintDialog1.PrinterSettings = PrintDocument1.PrinterSettings
PrintDialog1.AllowSomePages = True
When the application is compiled and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
Click the Print button to make the Print dialog box appear.
Visual Basic If Statement
In Visual Basic, If statement is useful to execute the block of code or statements conditionally based on the value of an
expression.
Generally, in Visual Basic, the statement that needs to be executed based on the condition is known as a “Conditional
Statement” and the statement is more likely a block of code.
If bool_expression Then
// Statements to Execute if condition is true
End If
If you observe the above If statement syntax, the statements inside of the If condition will be executed only when the
“bool_expression” returns true otherwise, those statements will be ignored for execution.
Following is the sample example of using the If statement in Visual Basic programming language.
Dim x As Integer = 20
If x >= 10 Then
Console.WriteLine("Number Greater than 10")
End If
If you observe the above example, the Console statement will be executed only when the defined condition (x >= 10)
returns true.
If you observe the above Visual Basic If statement flow chart diagram, when the defined condition is true, the
statements within the If condition will be executed; otherwise, the If condition will end without executing the
statements.
Visual Basic If Statement Example
Following is the example of defining the If statement in Visual Basic programming language to execute the block of
code or statements based on a Boolean expression.
Module Module1
Sub Main()
Dim x As Integer = 20, y As Integer = 10
If x >= 10 Then
Console.WriteLine("x is Greater than 10")
End If
If y <= 5 Then
Console.WriteLine("y is less than or equals to 5")
End If
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, we defined two If conditions to execute the statements based on the defined
variables (x, y) values.
When we execute the above Visual Basic program, we will get the result as shown below.
If you observe the above result, only one If condition is true that’s the reason only one statement printed on the
console window.
This is how we can use the If statement in Visual Basic programming language to execute the block of code or
statements based on our requirements.
VB.Net - Looping Statements
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
VB.Net provides following types of loops to handle looping requirements. Click the following links
to check their details.
VB.Net provides the following control statements. Click the following links to check their details.
Syntax
Generally, the Exit statement is written along with a condition. If the Exit condition is true inside the loop, it
exits from the loop and control transfer to the next statement, followed by the loop. And if
the Exit condition fails for the first time, it will not check any statement inside the loop and terminates the
program.
We will now see how to use the Exit statement in loops and Select case statements to finish the program's
execution in the VB.NET programming language.
Exit_While.vb
Imports System
Module Exit_While
Sub Main()
' Definition of count variable
Dim count As Integer = 1
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.
Imports System
Module Exit_For
Sub Main()
'Definition of num variable
Dim num As Integer
Dim sum As Double = 0.0
'Execution of For loop
For i As Integer = 1 To 10
'Accept a number from the user
Console.WriteLine("Enter a number : ")
num = Console.ReadLine()
' If the user enters a negative number, the loop terminates
If num < 0 Then
Exit For ' terminate the For loop
End If
sum += num
Next
Console.WriteLine(" Exit from the For loop when (num < 0) is: {0}", num)
Console.WriteLine(" Total sum is : {0}", sum)
Console.WriteLine(" Press any key to exit from the Console Screen")
Console.ReadKey()
End Sub
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.
Exit_Do_While.vb
Imports System
Module Exit_Do_While
Sub Main()
'Definition of the count variable
Dim count As Integer = 20
If count = 25 Then
Exit Do ' terminate the Do While loop
End If
Console.WriteLine(" Value of Count is : {0}", count)
count = count + 1
Loop While (count < 50)
Console.WriteLine(" Exit from the Do While loop when count = {0}", count)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
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.
Visual Basic Exit Statement
In visual basic, the Exit statement is useful to terminate the execution of loops (for, while, do-while, etc.) and transfers
the control immediately to the next statements that follow a terminated loops or statements.
In visual basic, we can also use Exit statement in nested loops to stop or terminate the execution of inner loops based
on our requirements.
Now, we will see how to use Exit statement in for loop, while loop, do-while loop to terminate the execution of loops
in a visual basic programming language with examples.
Following is the example of terminating the execution of for loop with Exit statement.
Module Module1
Sub Main()
For i As Integer = 1 To 4
If i = 3 Then Exit For
Console.WriteLine("i value: {0}", i)
Next
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above code, we used the Exit statement to terminate the for loop whenever the variable i value
equals 3.
When we execute the above visual basic program, we will get the result as shown below.
If you observe the above result, whenever the variable i value equals 3, the for loop execution automatically stops.
This is how we can use the Exit statement in for loop to terminate the execution of for loop based on our
requirements.
Following is the example of using Exit keyword in a while loop to terminate loop execution in a visual basic
programming language.
Module Module1
Sub Main()
Dim i As Integer = 1
While i < 4
Console.WriteLine("i value: {0}", i)
i += 1
If i = 2 Then Exit While
End While
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, whenever the variable (i) value become 2, we are terminating the while
loop using Exit statement.
When we execute the above visual basic program, we will get the result as shown below.
This is how we can use the Exit statement with the while loop to terminate the execution of the loop based on our
requirements.
Following is the example of using Exit keyword in a do-while loop to terminate loop execution in a visual basic
programming language.
Module Module1
Sub Main()
Dim i As Integer = 1
Do
Console.WriteLine("i value: {0}", i)
i += 1
If i = 2 Then Exit Do
Loop While i < 4
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
If you observe the above example, whenever the variable (i) value become 2, we are terminating the loop
using Exit statement.
We will get the following result when we execute the above visual basic program.
This is how we can use the Exit statement in the do-while loop to terminate the execution of the loop based on our
requirements.
This is how we can use the Exit statement in our visual basic applications to terminate the execution of loops or
statements based on our requirements.
Nested Control Structures VB Help
You can place, or nest, control structures inside other control structures (such as an If… Then
block within a For … Next loop). Control structures in Visual Basic can be nested in as many
levels as you want. It’s common practice to indent the bodies of nested decision and loop
structures to make the program easier to read. Here is the structure of a nested For … Next loop
that scans all the elements” of a two-dimensional array:
The outer loop (with the irow counter) scans each row of the array, and the inner loop scans
each column. The outer loop scans each element in the first row of-the array, the elements of the
second row, and so on, until the entire array has been scanned. The loop’s body can process the
element Array2/irow, icol).
You can also nest control flow structures. The following structure tests a user supplied value to
determine if it’s positive and, if so, determines whether the value exceeds a certain limit:
The Income variable is first compared with zero. If it’s negative, the Else clause of the U… Then
statement is executed-If it’s positive, it’s compared with the value 20000, and depending on the
outcome, a different message is displayed.
The Exit Statement
The Exit statement allows you to exit prematurely from a block of statements in a control
structure, from a loop, or even from a procedure. Suppose you have a For … Next loop that
calculates the square root of a ~es of numbers. Because the square root of negative numbers
can’t be calculated (the Sqr() function generates a runtime error), you might want to.halt the
operation if the array contains an invalid value. To exit the loop prematurely, use the Exit For
statement as follows:
If a negative element is found in this loop, the program exits.the loop and continues with the
statement following the Next statement.
There are similar Exit statements for the Do loop (Exit Do), as well as for functions and
subroutines (Exit Function and Exit Subroutine). If the previous loop was part of a function, you
might want to assign an error code to the function and exit not only the loop” but the function
itself:
If this code is part of a subroutine procedure, you use the Exit Subroutine statement. The
Exit statements for loops are Exit For and Exit Do. There is no way (or compelling reason) to exit
prematurely from an If or Case statement. There is also an Exit Property statement, which we’ll
look at in Chapter 16, Building Active Controls .
Nested Control Structures
You can place, or nest, control structures inside other control structures (such as an If. . .Then block
within a For. . .Next loop). Control structures in Visual Basic can be nested in as many levels as you
want. The editor automatically indents the bodies of nested decision and loop structures to make the
program easier to read.
When you nest control structures, you must make sure that they open and close within the same
structure. In other words, you can’t start a For. . .Next loop in an If statement and close the loop
after the corresponding End If. The following code segment demonstrates how to nest several flow-
control statements. (The curly brackets denote that regular statements should appear in their place
and will not compile, of course.)
For a = 1 To 100
{ statements }
If a = 99 Then
{ statements }
End If
While b < a
{ statements }
If total <= 0 Then
{ statements }
End If
End While
For c = 1 to a
{ statements }
Next c
Next aCode language: VB.NET (vbnet)
I’m showing the names of the counter variables after the Next statements to make the code more
readable. To find the matching closing statement (Next, End If, or End While), move down from the
opening statement until you hit a line that starts at the same column. This is the matching closing
statement. Notice that you don’t have to align the nested structures yourself; the editor reformats the
code automatically as you edit. It also inserts the matching closing statement— the End If statement
is inserted automatically as soon as you enter an If statement, for example.
Listing 3.6 shows the structure of a nested For. . .Next loop that scans all the elements of a two-
dimensional array.
You can also nest multiple If statements. The code in Listing 3.7 tests a user-supplied value to
determine whether it’s positive; if so, it determines whether the value exceeds a certain limit.
For i = 0 To UBound(nArray)
If nArray(i) < 0 Then
MsgBox("Can't complete calculations" & vbCrLf & _
"Item " & i.ToString & " is negative! "
Exit For
End If
nArray(i) = Math.Sqrt(nArray(i))
NextCode language: VB.NET (vbnet)
If a negative element is found in this loop, the program exits the loop and continues with the
statement following the Next statement.
There are similar Exit statements for the Do loop (Exit Do), the While loop (Exit While), the Select
statement (Exit Select), and for functions and subroutines (Exit Function and Exit Sub). If the
previous loop was part of a function, you might want to display an error and exit not only the loop,
but also the function itself by using the Exit Function statement.
VB.NET Arrays
An array is a linear data structure that is a collection of data elements of the same type stored on
a contiguous memory location. Each data item is called an element of the array. It is a fixed size of
sequentially arranged elements in computer memory with the first element being at index 0 and the last
element at index n - 1, where n represents the total number of elements in the array.
The following is an illustrated representation of similar data type elements defined in the VB.NET array data
structure.
In the above diagram, we store the Integer type data elements in an array starting at index 0. It will continue
to store data elements up to a defined number of elements.
In the above declaration, array_name is the name of an array, and the Data_Type represents the type of
element (Integer, char, String, Decimal) that will to store contiguous data elements in the VB.NET array.
Furthermore, we can also initialize and declare an array using the following ways, as shown below.
Let's create a program to add the elements of an array in VB.NET programming language.
num_Array.vb
1. Imports System
2. Module num_Array
3. Sub Main()
4. Dim i As Integer, Sum As Integer = 0
5. 'In VB.NET the size of an array is n+1
6. 'Declaration and Initialization of marks() array
7. Dim marks() As Integer = {58, 68, 95, 50, 23, 89}
8. Console.WriteLine(" Marks in 6 Subjects")
9. For i = 0 To marks.Length - 1
10. Console.WriteLine(" Marks {0}", marks(i))
11. Sum = Sum + marks(i)
12. Next
13. Console.WriteLine(" Grand total is {0}", Sum)
14.
15. Console.WriteLine(" Press any key to exit...")
16. Console.ReadKey()
17. End Sub
18. End Module
Output:
In the above program, we create an integer array with name marks() and define a For loop to access each
item of the array marks.
Input_array.vb
1. Imports System
2. Module Input_array
3. Sub Main()
4. 'Definition of array
5. Dim arr As Integer() = New Integer(5) {}
6. For i As Integer = 0 To 5
7. Console.WriteLine(" Enter the value for arr[{0}] : ", i)
8. arr(i) = Console.ReadLine() ' Accept the number in array
9. Next
10. Console.WriteLine(" The array elements are : ")
11. ' Definition of For loop
12. For j As Integer = 0 To 5
13.
14. Console.WriteLine("{0}", arr(j))
15. Next
16.
17. Console.WriteLine(" Press any key to exit...")
18. Console.ReadKey()
19. End Sub
20. End Module
Output:
Multidimensional Array
In VB.NET, a multidimensional array is useful for storing more than one dimension in a tabular form, such as
rows and columns. The multidimensional array support two or three dimensional in VB.NET.
MultidimenArray.vb
1. Imports System
2. Module MultidimenArray
3. Sub Main()
4. ' Definition of 2 Dimensional Array
5. Dim intArray(,) As Integer = {{5, 4}, {3, 2}, {4, 7}, {4, 5}}
6.
7. ' Definition of 3 Dimensional Array
8. Dim threeDimen(,,) As Integer =
9. {{{1, 3, 2}, {2, 3, 4}},
10. {{5, 3, 6}, {3, 4, 5}},
11. {{1, 2, 2}, {5, 2, 3}}}
12.
13. Console.WriteLine(" Two Dimensional Arraye in VB.NET are")
14. For i As Integer = 0 To 3
15. For j As Integer = 0 To 1
16. Console.WriteLine("intArray[{0}, {1}] = {2}", i, j, intArray(i, j))
17. Next j
18. Next i
19.
20. Console.WriteLine(" Three Dimensional Arraye in VB.NET are")
21. For i As Integer = 0 To 2 - 1
22. For j As Integer = 0 To 2 - 1
23. For k As Integer = 0 To 4
24. Console.WriteLine("intArray[{0}, {1}, {2}] = {3}", i, j, k, threeDimen(i, j, k))
25. Next k
26. Next j
27. Next i
28.
29. Console.WriteLine(" Press any key to exit...")
30. Console.ReadKey()
31. End Sub
32. End Module
Output:
Fixed Size Array
In VB.NET, a fixed- size array is used to hold a fixed number of elements in memory. It means that we have
defined the number of elements in the array declaration that will remain the same during the definition of
the elements, and its size cannot be changed. For example, we need to hold only 5 names in an array; it can
be defined and initialized in the array such as,
The above representation of the fixed array is that we have defined a string array names 0 to 4, which stores
all the elements in the array from 0 to index 4.
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.
You can also initialize the array elements while declaring the array. For example,
The elements in an array can be stored and accessed by using the index of the
array. The following program demonstrates this −
Live Demo
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the
need of the program. You can declare a dynamic array using the ReDim statement.
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.
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 −
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 following table provides some of the most commonly used properties of
the Array class −
IsFixedSize
1
Gets a value indicating whether the Array has a fixed size.
IsReadOnly
2
Gets a value indicating whether the Array is read-only.
Length
3 Gets a 32-bit integer that represents the total number of elements
in all the dimensions of the Array.
LongLength
4 Gets a 64-bit integer that represents the total number of elements
in all the dimensions of the Array.
Rank
5
Gets the rank (number of dimensions) of the Array.
The following table provides some of the most commonly used methods of
the Array class −
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: ")
When the above code is compiled and executed, it produces the following result −
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72
VB.NET Dynamic Array
A Dynamic array is used when we do not know how many items or elements to be inserted in an array. To
resolve this problem, we use the dynamic array. It allows us to insert or store the number of elements at
runtime in sequentially manner. A Dynamic Array can be resized according to the program's requirements at
run time using the "ReDim" statement.
The ReDim statement is used to declare a dynamic array. To resize an array, we have used
a Preserve keyword that preserve the existing item in the array. The array_name represents the name of the
array to be re-dimensioned. A subscript represents the new dimension of the array.
To initialize a Dynamic Array, we have used create a string array named myArr() that uses the Dim statement
in which we do not know the array's actual size. The ReDim statement is used to resize the existing array by
defining the subscript (3). If we want to store one more element in index 4 while preserving three elements
in an array, use the following statements.
Also, if we want to store multiple data types in an array, we have to use a Variant data type.
Dynamic_Arr.vb
Imports System
Module Dynamic_Arr
Sub Main()
'Declaration and Initialization of String Array Days()
Dim Days(20) As String
' Resize an Array using the ReDim Statement
ReDim Days(6)
Days(0) = "Sunday"
Days(1) = "Monday"
Days(2) = "Tuesday"
Days(3) = "Wednesday"
Days(4) = "Thursday"
Days(5) = "Friday"
Days(6) = "Saturday"
Output:
Adding New Element to an Array
When we want to insert some new elements into an array of fixed size that is already filled with old array
elements. So, in this case, we can use a dynamic array to add new elements to the existing array.
Let us create a program to understand how we can add new elements to a dynamic array.
Dynamic_Arr1.vb
Imports System
Module Dynamic_arr1
Sub Main()
'Declaration and Initialization of String Array Days()
Dim Days() As String
' Resize an Array using the ReDim Statement
ReDim Days(2)
Days(0) = "Sunday"
Days(1) = "Monday"
Days(2) = "Tuesday"
Console.WriteLine(" Before Preserving the Elements")
For i As Integer = 0 To Days.Length - 1
Console.WriteLine("Days Name in [{0}] index is {1}", i, Days(i))
Next
Console.WriteLine()
Output:
In the above program, we have created a dynamic array Days as a String that executes the first three
elements of Days such as Sunday, Monday, and Tuesday. we have also used a Preserve Keyword to keep
the existing elements of an array with new elements in dynamic array Days.
Subroutines and Functions
The code you write won’t be a monolithic listing. It will be made up of small segments called procedures and
you will work on one procedure at a time. This is called modularized approach of programming.
It permeates the Visual Basic language even the longest applications are written by breaking them into small,
well defined tasks. Each task is performed by a separate procedure that is written and tested separately from
the others. Procedures are useful for implementing repeated tasks.
The two types of procedures are subroutines and functions—the building blocks of your application.
Subroutines : A subroutine is a block of statements that carries out a well-defined task. The subroutine
begins with Sub and name of subroutine and its execution stops when EndSub statement is reached, and
control returns to the calling program. It is possible to exit a Subroutine prematurely with the Exit statement.
Functions : A function is similar to a subroutine, but a function returns a result. Subroutines perform a task
and don’t report anything to the calling program; functions commonly carry out calculations and report the
result. The statements that make up a function are placed in a pair of Function/End Function statements.
Because the function must report the result to the calling program, it must have a return type.
Subroutines
The idea of breaking a large application into smaller, more manageable sections is not new to
computing. Few tasks, programming or otherwise, can be managed as a whole. The event handlers
are just one example of breaking a large application into smaller tasks.
For example, when you write code for a control’s Click event, you concentrate on the event at hand
— namely, how the program should react to the Click event. What happens when the control is
double-clicked or when another control is clicked is something you will worry about later — in another
control’s event handler. This divide-and-conquer approach isn’t unique to programming events. It
permeates the Visual Basic language, and even the longest applications are written by breaking them
into small, well-defined, easily managed tasks. Each task is performed by a separate procedure that
is written and tested separately from the others. As mentioned earlier, the two types of procedures
supported by Visual Basic are subroutines and functions.
Subroutines usually perform actions and they don’t return any result. Functions, on the other hand,
perform some calculations and return a value. This is the only difference between subroutines and
functions. Both subroutines and functions can accept arguments, which are values you pass to the
procedure when you call it. Usually, the arguments are the values on which the procedure’s code
acts. Arguments and the related keywords are discussed in detail in the “VB.NET Arguments” section
later in this chapter.
A subroutine is a block of statements that carries out a well-defined task. The block of statements is
placed within a set of Sub. . .End Sub statements and can be invoked by name.
The following subroutine displays the current date in a message box and can be called by its name,
ShowDate():
Sub ShowDate()
MsgBox(Now().ToShortDateString)
End SubCode language: VB.NET (vbnet)
Normally, the task performed by a subroutine is more complicated than this; but even this simple
subroutine is a block of code isolated from the rest of the application. The statements in a subroutine
are executed, and when the End Sub statement is reached, control returns to the calling program. It’s
possible to exit a subroutine prematurely by using the Exit Sub statement.
All variables declared within a subroutine are local to that subroutine. When the subroutine exits, all
variables declared in it cease to exist.
Most procedures also accept and act upon arguments. The ShowDate() subroutine displays the
current date in a message box. If you want to display any other date, you have to implement it
differently and add an argument to the subroutine:
Sub Procedures:
A subprocedure is a group of VB.NET statements. It begins with a Sub keyword and ends with End
Sub keywords. A subprocedure is also called a subroutine. It is used to execute a certain block of
statements consists the body of the procedure. It is called explicitly by its name whenever it is
required to perform a certain task. It can be called any number of times. The subprocedure returns
control to the calling code after performing a task.
Structure of Subprocedure:
Sub <subname> [(parameter list)]
Vb statements
End Sub
Example:
Module module1
Sub SubDivide(ByVal num1 As Integer,
ByVal num2 As Integer)
End Sub
End Module
Output:
Function Procedures:
A function procedure is a group of VB.NET statements. It begins with a Function keyword and
ends with an End Function keyword. It is generally used to perform a task and return a value back
to the calling code. It may have multiple return points to the calling code. A part from return
stamens, End Function, or Exit function also returns control to the calling procedure.
Structure of Function Procedure:
Function <Functionname> [(parameter list)] As return type
Vb statements
End Function
Example:
Module module1
Function FunctionDivide(ByVal num1 As Integer,
ByVal num2 As Integer) As Integer
Console.WriteLine(res)
End Sub
End Module
A subprocedure does not return a value to the Functions return a value to the calling
3 calling code. code.
Subprocedure helps to make the code readable, In functions, it is not easy to modify
5 and easy to modify and debug. and debug the code.
In VB 6, the default argument-passing mechanism was by reference, and this is something you
should be aware of, especially if you’re migrating VB 6 code to VB 2008.
To specify the arguments that will be passed by value, use the ByVal keyword in front of the
argument’s name. If you omit the ByVal keyword, the editor will insert it automatically because it’s the
default option. To declare that the Degrees() function’s argument is passed by value, use the ByVal
keyword in the argument’s declaration as follows:
Celsius = 32.0
FTemp = Degrees(Celsius)
MsgBox(Celsius.ToString & " degrees Celsius are " & FTemp & _
" degrees Fahrenheit")Code language: VB.NET (vbnet)
This time the program displays the following message:
The function returns an integer, which is the number of values in the data set. The two important
values calculated by the function are returned in the Avg and StDev arguments:
The following code segment demonstrates this. The object is an ArrayList, which is an enhanced form
of an array. The ArrayList is discussed in detail later in the tutorial, but to follow this example all you
need to know is that the Add method adds new items to the ArrayList, and you can access individual
items with an index value, similar to an array’s elements. In the Click event handler of a Button
control, create a new instance of the ArrayList object and call the PopulateList() subroutine to
populate the list. Even if the ArrayList object is passed to the subroutine by value, the subroutine has
access to its items:
So far, to use a value in a procedure, we had to declare it. In some cases, a procedure may need an external
value in order to carry its assignment. A value that is supplied to a procedure is called an argument.
When creating a procedure that will use an external value, declare the argument that represents that value
between the parentheses of the procedure. For a sub procedure, the syntax you use would be:
Sub ProcedureName(Argument)
End Sub
Function Sub
The argument must be declared as a normal variable, omitting the Dim keyword. Here is an example that
creates a function that takes a string as argument:
Function CalculatePayroll(strName As String) As Double
Function Sub
A certain procedure can take more than one argument. In this case, in the parentheses of the procedure,
separate the arguments with a comma. Here is an example of a sub procedure that takes two arguments:
Sub EvaluateInvoice(EmplName As String, HourlySalary As Currency)
End Sub
In the body of a procedure that takes one or more arguments, use the argument(s) as you see fit as if they
were locally declared variables. For example, you can involve them with values inside of the procedure.
You can also exclusively use the values of the arguments to perform the assignment.
To call a procedure that takes an argument, type its name and a space, followed by a value for each
argument between parentheses. The value provided for an argument is also called a parameter. If there is
more than one argument, separate them with a comma. Here is an example:
Module Exercise
End Module
As mentioned previously, you can also use the Call keyword to call a procedure.
When you call a procedure that takes more than one argument, you must provide the values of the
arguments in the exact order they are listed inside of the parentheses of the function. Fortunately, you do
not have to. If you know the names of the arguments, you can type them in any order and provide a value
for each. To do that, on the right side of each argument, type the := operator followed by the desired value
for the argument. Here is an example:
Public Module Exercise
End Module
Practical Learning: Passing Arguments to a Procedure
1. To pass arguments to a function, change the file as follows (when you type the argument, Microsoft
Visual Studio, actually the Visual Basic language parser, will add the ByVal keywords; in the next
sections, we will learn what that keyword means; for now, keep but ignore it):
L = GetValue("Length")
W = GetValue("Width")
Perimeter = CalculatePerimeter(L, W)
End Module
6. When calling a procedure that takes an argument, we were supplying a value for that argument.
When this is done, the procedure that is called makes a copy of the value of the argument and makes
that copy available to the calling procedure. That way, the argument itself is not accessed. This is
referred to as passing an argument by value. This can be reinforced by typing the ByVal keyword on
the left side of the argument. Here is an example:
7. Private Sub Welcome(ByVal strLanguage As String)
8. MsgBox("Welcome to the wonderful world of " & strLanguage)
9. End Sub
10. If you create a procedure that takes an argument by value and you have used the ByVal keyword on
the argument, when calling the procedure, you do not need to use the ByVal keyword; just the name
of the argument is enough, as done in the examples on arguments so far. Here is an example:
11. Public Module Exercise
12.
13. Public Function Main() As Integer
14. Dim ComputerLanguage As String = "Visual Basic"
15.
16. Welcome(ComputerLanguage)
17. Return 0
18. End Function
19.
20. Private Sub Welcome(ByVal strLanguage As String)
21. MsgBox("Welcome to the wonderful world of " & strLanguage)
22. End Sub
23.
24. End Module
25. This would produce:
Passing Arguments By Reference
An alternative to passing arguments as done so far is to pass the address of the argument to the called
procedure. When this is done, the called procedure does not receive a simple copy of the value of the
argument: the argument is accessed by its address. That is, at its memory address. With this technique, any
action carried on the argument will be kept. If the value of the argument is modified, the argument would
now have the new value, dismissing or losing the original value it had. This technique is referred to as
passing an argument by reference. Consider the following program:
Public Module Exercise
End Module
To pass an argument by reference, on its left, type the ByRef keyword. This is done only when creating the
procedure. When the called procedure finishes with the argument, the argument would keep
whatever modification was made on its value. Now consider the same program as above but with arguments
passed by reference:
Public Module Exercise
End Module
Using this technique, you can pass as many arguments by reference and as many arguments by value as you
want. As you may guess already, this technique is also used to make a sub procedure return a value, which a
regular sub routine cannot do. Furthermore, passing arguments by reference allows a procedure to return as
many values as possible while a regular function can return only one value.
GetValues(L, W)
ShowCharacteristics(L, W)
Return 0
End Function
End Module
Generally, while calling the method we need to pass all the method parameters. In case, if we specify a few of method
parameters as an optional, then we can omit those parameters while calling the method because the optional
parameters are not mandatory.
If we want to make the parameter as an optional, we need to define a parameter with Optional keyword and assign the
default value to that parameter as part of its definition in methods, indexers, constructors, and delegates.
While calling the method, if no argument is sent for an optional parameter, then the default value will be used otherwise
it will use the value which is sent for that parameter.
Public Sub GetDetails(ByVal id As Integer, ByVal name As String, Optional ByVal location
As String = "Hyderabad")
' your code
End Sub
If you observe the above method, we made the location parameter as optional by assigning the default value
(Hyderabad). So, while accessing GetDetails() method, if no argument sent for location parameter, then by default it
will consider “Hyderabad” value otherwise it will use the value which is sent for that parameter.
GetDetails(1,"Suresh");
GetDetails(1,"Suresh", "Chennai");
While defining the optional parameters, we need to make sure that the optional parameters are defined at the end of
the parameter list, after any required parameters like as we defined in the above method otherwise we will get the
compile-time error like “optional parameters must appear after all required parameters”.
Public Sub GetDetails(ByVal id As Integer, Optional ByVal name As String = "Suresh", Opt
ional ByVal location As String = "Hyderabad")
' your code
End Sub
The defined GetDetails() method can be accessed like as shown below.
GetDetails(1);
GetDetails(1, "Rohini");
GetDetails(1, "Trishi", "Guntur");
While calling the method, if we provide an argument for any of succession optional parameters, then we must need to
provide an argument for all the preceding optional parameters and the comma-separated gaps in the argument list are
not supported.
GetDetails(1, , "Guntur");
The above caller method will throw a compile-time error like “Argument missing” because we provided an argument
for the third parameter but not for a second.
However, if you know the name of the third parameter, then you can use a named argument to send a value like as
shown below.
GetDetails(1, location:="Guntur");
This is how we can skip preceding optional parameters by using named arguments in caller methods.
Module Module1
Sub Main(ByVal args As String())
GetDetails(1)
GetDetails(1, "Rohini")
GetDetails(1, "Trishi", "Guntur")
GetDetails(1, location:="Guntur")
Console.ReadLine()
End Sub
Public Sub GetDetails(ByVal id As Integer, Optional ByVal name As String = "Suresh",
Optional ByVal location As String = "Hyderabad")
Console.WriteLine("Id:{0}", id)
Console.WriteLine("Name:{0}", name)
Console.WriteLine("Location:{0}", location)
End Sub
End Module
If you observe the above example, the GetDetails() method has one required parameter (id) and two optional
parameters (name, location).
When we execute the above program, we will get the result like as shown below.
****Only Required Parameter****
Id:1
Name:Suresh
Location:Hyderabad
This is how we can define the optional parameters in methods, indexers, constructors, and delegates based on our
requirements.
In visual basic, we can also achieve the optional parameters by using method overloading functionality. Generally,
the method overloading functionality will allow us to create multiple methods with the same name but with different
parameters.
To know more about overloading functionality in visual basic, check method overloading.
The optional parameters have been introduced to specify the parameters as optional while defining
the methods, indexers, constructors, and delegates.
To make the parameter as optional, we need to assign the default value to that parameter as part of its definition
in methods, indexers, constructors, and delegates.
While calling the method, if no argument is sent for an optional parameter, then the default value will be used.
While defining the optional parameters, we need to make sure that the optional parameters are defined at the
end of the parameter list, after any required parameters.
Visual Basic Named Parameters
In visual basic, the named parameters have been introduced to pass the method arguments with parameter name rather than
with the method parameter’s position in the parameter list.
Generally, while calling the method we need to pass all the method arguments in the same sequence of parameters in the
method definition. If we use named parameters, we don’t need to worry about the order or sequence of parameters while
calling the method.
In named parameters, the parameter values will be mapped to the right parameter based on the parameter name. So, while
calling the methods we can send the parameters in any sequence or order if we specify the parameter name.
For example, we have a GetDetails() method with three parameters (id, name, location) like as shown below.
Public Sub GetDetails(ByVal id As Integer, ByVal name As String, ByVal location As String)
' your code
End Sub
In the standard way, we will call the above method by sending the arguments in the same order or position however we
defined the parameters in the method definition like as shown below.
GetDetails("Trishi", 1, "Guntur");
By using named parameters, we call the above method by sending the parameters in any sequence or order like as shown
below.
Module Module1
Sub Main(ByVal args As String())
GetDetails(1, "Suresh", "Hyderabad")
GetDetails(name:="Rohini", id:=2, location:="Guntur")
GetDetails(3, "Trishi", location:="Guntur")
Console.ReadLine()
End Sub
Public Sub GetDetails(ByVal id As Integer, ByVal name As String, ByVal location As Strin
g)
Console.WriteLine("Id:{0}", id)
Console.WriteLine("Name:{0}", name)
Console.WriteLine("Location:{0}", location)
End Sub
End Module
If you observe the above example, we are calling the GetDetails() method by sending the parameters in different positions
with named parameters.
When we execute the above visual basic program, we will get the result like as shown below.
The named parameters have been introduced in visual basic to pass the method arguments with parameter name
rather than with the method parameter’s position in the parameter list.
In named parameters, the parameter values will be mapped to the right parameter based on the parameter name.
We can send the parameters in any sequence or order if we specify the parameters name while calling the methods.
While calling the method, we can use the named arguments with positional arguments as long as they are not
followed by any positional arguments.
Named Arguments
You learned how to write procedures with optional arguments and how to pass a variable number of
arguments to the procedure. The main limitation of the argument-passing mechanism, though, is the
order of the arguments. By default, Visual Basic matches the values passed to a procedure to the
declared arguments by their order (which is why the arguments you’ve seen so far are called
positional arguments).
This limitation is lifted by Visual Basic’s capability to specify named arguments. With named
arguments, you can supply arguments in any order because they are recognized by name and not by
their order in the list of the procedure’s arguments. Suppose you’ve written a function that expects
three arguments: a name, an address, and an email address
To test this technique, enter the following function declaration in a form’s code:
Debug.WriteLine(Name)
Debug.WriteLine(Address)
Debug.WriteLine(EMail)
Return ("OK")
Debug.WriteLine( _
Contact(Address:="2020 Palm Ave., Santa Barbara, CA 90000", _
Name:="Peter Evans", EMail:="[email protected]"))Code language: VB.NET (vbnet)
You’ll see the following in the Immediate window:
Peter Evans
2020 Palm Ave., Santa Barbara, CA 90000
[email protected]
OK
The function knows which value corresponds to which argument and can process them the same way
that it processes positional arguments. Notice that the function’s definition is the same, whether you
call it with positional or named arguments. The difference is in how you call the function and not how
you declare it.
Named arguments make code safer and easier to read, but because they require a lot of typing, most
programmers don’t use them. Besides, when IntelliSense is on, you can see the definition of the
function as you enter the arguments, and this minimizes the chances of swapping two values by
mistake.