Unit III - Introduction To VB
Unit III - Introduction To VB
INTRODUCTION TO VB .NET
The VB.NET stands for Visual Basic. Network Enabled Technologies. It is a simple, high-
level, object-oriented programming language developed by Microsoft in 2002. It is a
successor of Visual Basic 6.0, that is implemented on the Microsoft .NET framework.
Furthermore, it supports the OOPs concept, such as abstraction, encapsulation, inheritance,
and polymorphism. Therefore, everything in the VB.NET language is an object, including all
primitive data types (Integer, String, char, long, short, Boolean, etc.), user-defined data types,
events, and all objects that inherit from its base class. It is not a case sensitive language,
whereas, C++, Java, and C# are case sensitive language.
Applications built using the VB.NET language are very reliable and scalable, relying on the
.NET Framework to access all libraries that help to execute a VB.NET program. With this
language, you can develop a fully object-oriented application that is similar to an application
created through another language such as C++, Java, or C#. In addition, applications or
programs of VB.NET are not only running on the window operating system but can also run
on Linux or Mac OS.
The VB.NET language is designed in such a way that any new beginner or novice and the
advanced programmer can quickly develop a simple, secure, robust, high performance of
web, windows, console, and mobile application running on .NET Framework.
VB.NET FEATURES
As we know, it is a high-level programming language with many features to develop a secure
and robust application. These are the following features that make it the most popular
programming language.
ADVANTAGES OF VB.NET
The VB.NET executes a program in such a way that runs under CLR (Common
Language Runtime), creating a robust, stable, and secure application.
It is a pure object-oriented programming language based on objects and classes.
However, these features are not available in the previous version of Visual Basic 6.
That's why Microsoft launched VB.NET language.
Using the Visual Studio IDE, you can develop a small program that works faster, with
a large desktop and web application.
The .NET Framework is a software framework that has a large collection of libraries,
which helps in developing more robust applications.
It uses drop and drag elements to create web forms in .NET applications.
However, a Visual Basic .NET allows to connect one application to another
application that created in the same language to run on the .NET framework.
A VB.NET can automatically structure your code.
The Visual Basic .NET language is also used to transfer data between different layers
of the .NET architecture such that data is passed as simple text strings.
It uses a new concept of error handling in the Visual Basic .NET Framework. The
new structure is the try, catch, and finally method used to handle exceptions as a unit.
In addition, it allows appropriate action to be taken at the place where it encountered
an error. In this way, it discourages the use of the ON ERROR GOTO statement in
.NET programming.
DISADVANTAGES OF VB.NET
Also, notice: In Windows, there are multiple methods for doing the same thing. There is no
need to have mastery on all these methods. Use any one method that you find the most
comfortable.
Right-click the Start-button. A menu pops up on the screen as shown in Figure 3.1. Click the
menu-item Open All Users, and the Windows Explorer pops up on the screen as shown in
Figure 3.2 and it is captioned as “Start Menu” (keep the Windows Explorer in maximized
mode. I have resized the figure to save space). Notice the folder captioned Programs in the
right pane of the Windows Explorer. Double-click this Programs folder, and the caption of
Windows Explorer changes to Programs as shown in Figure 3.3. Find the folder Microsoft
Visual Studio .NET in the right pane of the Windows Explorer (use scrollbar, if needed).
Double click this Microsoft Visual Studio .NET folder, and the caption of Windows Explorer
changes to Microsoft Visual Studio .NET as shown in Figure 3.4. Right-click the icon
Microsoft Visual Studio .NET in the right pane of Windows Explorer and a menu pops up on
the screen as shown in Figure 3.5(a). Click the menu-item Copy, now the menu disappears
from the screen.
Figure 3.1 Right-click the Start-button on the extreme left end of the taskbar and this menu pops up on the
screen. Now click the menu-item Open All Users and the Windows Explorer (captioned as Start Menu) pops
up on the screen as shown in Figure 3.2.
Figure 3.2 Click the menu-item Open All Users shown in Figure 3.1, and the Windows Explorer pops up on
the screen as shown in this figure. Now double-click the folder Programs in the right-pane and contents of
Windows Explorer changes as shown in Figure 3.3.
Click the minimize-window-button of the Windows Explorer. It minimizes, and joins the
taskbar. Now place the mouse-cursor anywhere on the wallpaper (but not on any window,
icon, or taskbar) and right-click, and a menu pops up on the screen as shown in Figure 3.5(b).
Click the menu-item Paste, and the menu disappears from the screen. The icon captioned as
Microsoft Visual Studio .NET, which represents the shortcut to Microsoft Visual Studio
.NET program, pops up on the screen. You can double click this icon to start the Microsoft
Visual Studio .NET program. Click the minimized Windows Explorer lying on the taskbar
and it reappears. Click the close-window-button of the Windows Explorer and it closes.
Now drag the icon Microsoft Visual Studio .NET (i.e. shortcut) to a suitable position on the
wallpaper. In order to drag this icon, place the mouse-cursor on it, press the left-button of the
mouse, drag the mouse-cursor to a desired location on the wallpaper, and then release the
left-button. Now you can double-click the shortcut icon Microsoft Visual Studio .NET in
order to start the program.
Figure 3.3 Double-click the folder captioned as Microsoft Visual Studio .NET and the contents of Windows
Explorer change as shown in Figure 3.4.
Figure 3.4 Right-click the icon captioned as Microsoft Visual Studio.NET and a menu-pops up on the screen
as shown in Figure 3.5(a).
Figure 3.5 Right-click the icon Microsoft Visual Studio .NET and the menu shown in (a) pops up on the
screen. Click the menu-item Copy. Then right-click the wallpaper and the menu shown in (b) pops up on the
screen. Click the menu-item Paste, and the shortcut icon shown in the (c) pops up on the screen.
Figure 3.6 Displaying the form window on the screen. Click the + sign shown in (a) and then double-click the
form icon shown in (b).
You can also use the Standard toolbar to open the various windows. You can use the
following tools on the Standard toolbar to open the corresponding windows (simply click that
tool to open the window): Solution Explorer, Properties Window, Toolbox, Class View,
Server Explorer, Resources View, Object Browser, and Output.
Among the toolbars, the Standard toolbar is always displayed on the screen. In addition, other
toolbars appear (on the screen) and disappear (from the screen) automatically, as per
requirement. For example, when you open or close the form window, the Layout toolbar
appears on or disappears from the screen automatically. The various toolbars available in
Visual Basic .NET are listed below:
In order to open or close any toolbar, you are required to use the View-menu. For example, if
you want to open the Table toolbar, then use one of the methods given below:
1. Choose View | Toolbars | Table, and the Table toolbar appears on the screen.
2. Right-click the menubar (or any toolbar) and a menu pops up on the screen as shown
in Figure 3.7 (this is the same menu you get when you choose View | Toolbars). Click
the menu-item Table, and the Table toolbar appears on the screen.
Figure 3.7 The Toolbars-menu (cropped to save space). Choose View | Toolbars, (or right-click
menubar or any toolbar) to access this menu. You can click menu-items on this menu to open or
close a toolbar.
If you want to close the Table toolbar, then use one of the methods given below (which are
precisely the same as the ones given above):
1. Choose View | Toolbars | Table, and the Table toolbar disappears from the screen.
2. Right-click the menubar (or any toolbar), and a menu pops up on the screen as shown
in Figure 3.7 (this is the same menu you get when you choose View | Toolbars). Click
the menu-item Table, and the Table toolbar disappears from the screen.
Also, notice that a check-mark on the Toolbars menu (see Figure 3.7) indicates that the
toolbar is displayed on the screen. For example, in Figure 3.7, the menu-items Standard and
Layout are checked indicating that these toolbars are displayed on the screen.
tool is disabled then: (a) you must click the close-window-button of that window to close it,
and (b) the tab of that window (like Toolbox tab shown in Figure 3.8) disappears. You must
use the View-menu or Standard toolbar to open that window again. A Toolbox that slides on
and off the screen is uncomfortable to use and also overlaps the form causing inconvenience.
Therefore, let us nail down the Toolbox so that it always remains on the screen and doesn’t
overlap the form as shown in Figure 3.10. Choose View | Toolbox, and the Toolbox appears
on the screen. Click the Auto Hide tool so that it becomes disabled as shown in Figure 3.10.
Figure 3.8 Click the Start Page tab to bring the Start Page to the front, and so on. Also, click the Toolbox tab
and the Toolbox slides on the screen as shown in Figure 3.13, thanks to Auto Hide facility.
Figure 3.9 When you click the Toolbox tab, the Toolbox slides on the screen (appears on the screen). Now
click anywhere in the form window (but not on the Toolbox) and Toolbox slides off the screen (disappears
from the screen), thanks to Auto Hide facility.
Figure 3.10 If Auto Hide tool of Toolbox is disabled then it doesn’t overlap the form window as shown in this
figure.
If you double-click the titlebar of a docked window (with Auto Hide facility disabled) then
the docked window instantly gets converted into undocked (or floating window). Figure 3.11
(a) shows a docked window (with Auto Hide facility disabled) and Figure 3.11 (b) shows
undocked or floating window.
If you double-click the titlebar of an undocked (or floating) window then it gets converted
into a docked window (with Auto Hide facility disabled).
If you right-click the titlebar of any window, then a menu pops up on the screen as shown in
Figure 3.11(c). In the figure the menu-item Dockable is checked because that is the current
status of the window. Now you can click any menu-item to change the status of the window
accordingly.
Figure 3.11 Docked and undocked windows. Double-click the title-bar of either window shown in (a) or (b),
and it toggles between the docked and undocked states. In (c), checked menu-item indicates the current status
of window. Click the desired menu-item to change the status of a window accordingly.
This procedure is as follows: Place the mouse-cursor on the titlebar of a window, press the
left button of the mouse (and hold it down), drag the mouse-cursor to the desired location on
the screen, the ghost image of the window also moves with the mouse-cursor. When ghost
image arrives at the desired location, stop dragging the mouse-cursor, release the left button
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 8
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
of the mouse, and now the window gets moved or relocated successfully to the desired
location. While dragging the mouse-cursor you can press the Ctrl key to prevent the docking
of a window. Also, when you attempt to move or relocate a docked window (with Auto Hide
facility disabled), it instantly gets converted into an undocked (or floating) window.
RESIZING A WINDOW
You can resize a window (docked or undocked, Auto Hide enabled or disabled) in Visual
Studio .NET. The procedure of resizing a window in Visual Studio .NET is the same as that
of Windows XP.
This procedure is as follows: Place the mouse-cursor on the boundary of the window so that it
looks like a double-tipped arrow, press the left button of the mouse (and hold it down), drag
the mouse cursor in the inward or outward direction. As you drag the mouse-cursor, the ghost
boundary of the window also moves with it. When ghost boundary of the window indicates
the desired size, then stop dragging the mouse-cursor, release the left button of the mouse,
and the window gets resized successfully. Now let us conclude this lesson. Firstly, let us
close the solution (or project), choose File | Close Solution, (if a message-box pops up on the
screen asking you whether to save the changes, click the No button) and the solution closes.
Choose File | Exit, and the Visual Studio .NET shuts down.
VB .NET FORMS
Let's start with creating a Window Forms Application by following the following steps in
Microsoft Visual Studio - File → New Project → Windows Forms Applications
Finally, select OK, Microsoft Visual Studio creates your project and displays following
window Form with a name Form1.
VB.Net Form
Visual Basic Form is the container for all the controls that make up the user interface. Every
window you see in a running visual basic application is a form, thus the terms form and
window describe the same entity. Visual Studio creates a default form for you when you
create a Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there will be
buttons to close, maximize and minimize the form shown below −
Form Properties
Following table lists down various important properties related to a form. These properties
can be set or read during application execution. You can refer to Microsoft documentation for
a complete list of properties associated with a Form control –
The button that's automatically activated when you hit the Esc
key.
2 CancelButton
Usually, the Cancel button on a form is set as CancelButton for
a form.
This property lets you specify the minimum size of the form,
5 AutoScrollMinSize
before the scroll bars are attached.
15 MaximizeBox By default, this property is True and you can set it to False to
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 11
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
20 Text The text, which will appear at the title bar of the form.
Form Methods
The following are some of the commonly used methods of the Form class. You can refer to
Microsoft documentation for a complete list of methods associated with forms control –
5 CenterToParent - Centers the position of the form within the bounds of the parent form.
Contains - Retrieves a value indicating whether the specified control is a child of the
8
control.
Refresh - Forces the control to invalidate its client area and immediately redraw itself
11
and any child controls.
12 Scale(SizeF) - Scales the control and all child controls by the specified scaling factor.
Form Events
Following table lists down various important events related to a form. You can refer to
Microsoft documentation for a complete list of events associated with forms control −
10 KeyDown Occurs when a key is pressed while the form has focus.
11 KeyPress Occurs when a key is pressed while the form has focus.
12 KeyUp Occurs when a key is released while the form has focus.
Occurs when the mouse pointer is over the form and a mouse
15 MouseDown
button is pressed.
19 MouseMove Occurs when the mouse pointer is moved over the form.
Occurs when the mouse pointer is over the form and a mouse
20 MouseUp
button is released.
Occurs when the mouse wheel moves while the control has
21 MouseWheel
focus.
24 Scroll Occurs when the user or code scrolls through the client area.
Example
Following is an example, which shows how we create two buttons at the time of form load
event and different properties are being set at the same time.
Because Form1 is being referenced within its own event handler, so it will be written as Me
instead of using its name, but if we access the same form inside any other control's event
handler, then it will be accessed using its name Form1.
Let's double click on the Form and put the follow code in the opened window.
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window –
TOOLBOX WINDOW
The Toolbox window contains all the controls you can use to build your application’s
interface. This window is usually retracted, and you must move the pointer over it to view the
Toolbox. The controls in the Toolbox are organized in various tabs, so take a look at them to
become familiar with the controls and their functions.
The Common Controls tab contains the icons of the most common Windows controls. The
Data tab contains the icons of the objects you will use to build data-driven applications
(they’re explored later in this tutorial). The Dialogs tab contains controls for implementing
the common dialog controls, which are so common in Windows interfaces.
If the solution contains multiple projects, you can right-click the project you want to become
the startup form and select Set As StartUp Project. You can also add items to a project with
the Add Item command of the context menu, or remove a component from the project with
the Exclude From Project command. This command removes the selected component from
the project, but doesn’t affect the component’s file on the disk. The Delete command removes
the selected component from the project and also deletes the component’s file from the disk.
PROPERTIES WINDOW
This window (also known as the Properties Browser) displays all the properties of the
selected component and its settings. Every time you place a control on a form, you switch to
this window to adjust the appearance of the control. You have already seen how to
manipulate the properties of a control through the Properties window.
Many properties are set to a single value, such as a number or a string. If the possible settings
of a property are relatively few, they’re displayed as meaningful constants in a drop-down
list. Other properties are set through a more elaborate interface. Color properties, for
example, are set from within a Color dialog box that’s displayed right in the Properties
window. Font properties are set through the usual Font dialog box. Collections are set in a
Collection Editor dialog box, in which you can enter one string for each item of the
collection, as you did for the items of the ComboBox control.
If the Properties window is hidden, or if you have closed it, you can either choose View >
Properties Window, or right-click a control on the form and choose Properties. Or you can
simply press F4 to bring up this window. There will be times when a control might totally
overlap another control, and you won’t be able to select the hidden control and view its
properties. In this case, you can select the desired control in the ComboBox at the top of the
Properties window. This box contains the names of all the controls on the form, and you can
select a control on the form by selecting its name on this box.
Figure 3.16 The Properties window. Choose View | Properties Window to access it.
Click the object for which you intend to write an event procedure and then click the View
Code tool on Solution Explorer window (Figure 3.15, b). Now Visual Basic opens the code
window for you.
Right-click form (or control). A menu pops up on the screen. Click the menu-item View
Code—the menu disappears and the code window opens.
To close the code window, simply click its close-window-button. Now let us write an event
procedure for the button btnExit such that the former should be executed when a user clicks
the latter. Here, mouse-click is an event; and when this event takes place with button btnExit,
the event procedure gets executed. Notice:
Note:
In Visual Basic, a typical event procedure is written for a particular event (e.g. click,
double-click, etc.) and attached to a particular object (e.g. form, label, button, etc.). For
example, you can write an event procedure for a button for an event of mouse-click.
During run-time, whenever a user clicks that button, the corresponding event procedure is
executed.
Double click the button btnExit, and the code window opens (Figure 3.17). Notice that this
code window consists of two drop-down-list-boxes and an edit-box. The drop-down-list-
boxes are named as Class Name and Method Name (Figure 3.17, a). The drop-down-list-box
Class Name displays the list-item frmHello and the drop-down-list-box Method Name
displays the list-item btnExit_Click. Event procedure is also called method (actually, method
is more generic than event procedure, but I want to avoid details at this early stage). Here,
btnExit_Click ( ) is the name of the event procedure. As a convention, a pair of empty
parentheses is written after the name of an event procedure so that the reader can understand
that it is the name of the event procedure.
The code window shown in Figure 3.17 is all set to accept the code for button btnExit for the
event of Click (i.e. mouse-click). We have double-clicked the button btnExit, and Visual
Basic has correctly guessed that we are going to write an event procedure for button btnExit
for the event of Click. Lastly, note that apart from mouse-click, a number of events are
associated with button, and you can write the event procedures for all these events (such as
KeyPress, KeyDown, MouseUp, and so on). But for now think of mouse-click only.
Figure 3.17 Code window. Choose View | Code (or double-click the form or object), to access it. This code
window is opened by double-clicking the button btnExit.
Now take a look at the edit-box. Two lines of code (text) are already written for you and the
keyboard-cursor (or insertion point) is blinking between these two lines (as shown in Figure
3.17, a), called wrappers or wrapper lines. The upper wrapper line is also called an opening
wrapper line while the lower wrapper line is called a closing wrapper line. Do not disturb the
wrapper lines. Type the following text (code) between the two wrapper lines:
End
Ensure that the event procedure btnExit_Click ( ) in your code window resembles the one
shown in Figure 3.17(b). Now the edit-box of the code window on your screen will display
the following three lines of code, among the other code lines:
Line 1 (opening wrapper line) tells the compiler that this is the beginning of the event
procedure. The term “btnExit_Click ( )” is the name of the event procedure. The syntax of the
name of event procedure is as follows:
objectName_eventName ( )
The name of event procedure “btnExit_Click ( )” tells the compiler that this event procedure
is for the object named btnExit and for the event named Click (i.e. mouse-click). The term
“Sub” in this line stands for Subprogram. The event procedure is a sort of subprogram. The
explanation of the term Private in line 1 is deferred to a later part of this book. However,
notice that most of the event procedures begin either with the word Private or Public.
There is lot of stuff in line 1 (particularly in the parentheses). Fortunately, you are not
required to know the details. The stuff in parentheses takes care of “argument passing.” In the
latter part of this book we will meet argument passing again. For now, it is enough for you to
know the meaning of the first three words in line 1, namely: Private, Sub, and btnExit_Click.
The terms “Private,” “Sub,” “Handles” and “End” possess predefined meaning in Visual
Basic. These are keywords (or reserved words). Notice:
Note:A keyword (or reserved word) in a language has a predefined meaning and it cannot
be used for any other purpose such as naming the object or variable.
Line 3 consists of only two words, namely: End and Sub. Line 3 tells the compiler that this is
the end of the event procedure. The terms “End” and “Sub” in line 3 tell the compiler that the
Subprogram has Ended.
Line 2 constitutes the main part of this event procedure. This is the line that actually does
some work, as the first and last lines (the wrappers) simply signal the start and end of event
procedure. Here, line 2 consists of a single term “End.” This line asks the compiler to
terminate the execution of application. Now, you can terminate your application simply by
clicking the button btnExit, there is no need to click the close-window-button of the form
window.
Choose Debug | Start (or click the Start tool on the Standard toolbar, or strike the function
key F5), and the application executes. Your screen now displays the run-time application
shown in Figure 3.18. Click the button Exit, the application terminates indicating that the
event procedure works correctly.
Figure 3.18 Run-time view of the Hello application. The text “Hello Boys and Girls” is written on the label
control and not on the form, but the label is borderless and hence invisible. You can click the button Exit to
terminate this program. Clicking close-window-button also works.
C:\VB\Hello\bin
and strike the Enter key. Now the right-pane of Explorer displays the two file icons and one
of them is Hello.exe (see Figure 3.19).
Double-click the file-icon Hello.exe. The stand alone application Hello executes and the form
shown in Figure 2.18 pops up on the screen. This stand alone application is working
correctly.
Figure 3.19 Executing the stand alone version of Hello application using the Windows Explorer. Double-
click the file icon Hello.exe and the application Hello executes.
VB.NET KEYWORDS
A keyword is a reserved word with special meanings in the compiler, whose meaning cannot
be changed. Therefore, these keywords cannot be used as an identifier in VB.NET
programming such as class name, variable, function, module, etc.
There are following reserved keyword available in the VB.NET language.
GetXML
Global GoTO Handles If Implements
Namespace
Not Not
Nothing Object Of On
Inheritable Overridable
VB.NET IDENTIFIERS
As the name defines, an identifier is used to identify the name of variable, function, class, or
any other user-defined elements in the program. An identifier should be the combination of
letter, digit, and underscore. Still, the first character of the identifier or variable name should
start with alphabet letter or underscore (_) of any length.
There are various rules for identifier in VB.NET, as follows:
The first character of an identifier must start with an alphabet or underscore, that
could be followed by any sequence of digits (0-9), letter or underscore.
An identifier should not contain any reserved keyword.
It should not start with any digit.
VB.NET COMMENTS
A comment is used to explain the various steps that we have taken in our programming. The
compiler ignores these comment statements because the compiler is not executed or
processed in VB.NET. Therefore, it does not take any place in your compilation code.
Syntax:
Dim Variable_Name as DataType
VariableName: It defines the name of the variable that you assign to store values.
DataType: It represents the name of the data type that you assign to a variable.
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 23
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
-1.79769313486231570E+308 to -4.94-
65645841246544E-324 for negative values;
Double 8 bytes
4.94065645841246544E-324 to
1.79769313486231570E+308, for positive values
-9,223,372,036,854,775,808 to
Long 8 bytes
9,223,372,036,854,775,807 (9.2…E + 18) (signed)
(unsigned)
User- A user-defined data type Each member of the structure has its own data
Defined depends on the type and limits independent of the other members'
(structure) implementing platform ranges.
Syntax:
Dim [Variable_Name] As [Defined Data Type]
Name Descriptions
It is used to declare and allocate the space for one or more variables in
Dim
memory.
Variable_Name It defines the name of the variable to store the values.
It is a keyword that allows you to define the data type in the declaration
As
statement.
It defines a data type that allows variables to store data types such as Char,
Data Type
String, Integer, Decimal, Long, etc.
Value Assign a value to the variable.
There are some valid declarations of variables along with their data type definition, as shown
below:
Dim Roll_no As Integer
Dim Emp_name As String
Dim Salary As Double
Syntax
Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3 As
DataType3
Note: The statements given below is also used to declare the variable with their data type:
Syntax:
Variable_name = value
For example:
Dim Roll_no As Integer 'declaration of Roll_no
Variable1.vb
Imports System
Module Variable1
Sub Main()
'declaration of intData as Integer
Dim intData As Integer
'declaration of charData as Char
Dim CharData As Char
'declaration of strData as String
Dim strData As String
'declaration of dblData as Double
Dim dblData As Double
'declaration of single_data as Single
Dim single_data As Single
'Initialization of intData
intData = 10
'Initialization of CharData
CharData = "A"
'Initialization of strData
strData = " VB.NET is a Programming Language."
dblData = 4567.676
'Initialization of dblData
'Initialization of single_data
single_data = 23.08
Console.WriteLine(" Value of intData is: {0}", intData)
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 27
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
User_Data.vb
Imports System
Module User_Data
Sub Main()
Dim num As Integer
Dim age As Double
Dim name As String
Console.WriteLine("Enter your favourite number")
' Console.ReadLine or Console.ReadLine() takes value from the user
num = Console.ReadLine
Console.WriteLine(" Enter Your Good name")
'Read string data from the user
name = Console.ReadLine
Console.WriteLine(" Enter your Age")
age = Console.ReadLine
Console.WriteLine(" You have entered {0}", num)
Console.WriteLine(" You have entered {0}", name)
Console.WriteLine(" You have entered {0}", age)
Console.ReadKey()
End Sub
End Module
Output:
Enter your favourite number
7
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 28
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
Note: Console.Read and Console.ReadKey() function is used to read a single character from
the user.
Example:
Dim num As Integer
Num = 5
Or
Dim num As Integer = 5
But when we write the following statement, it generates a compile-time error because it is not
a valid statement.
Dim x As Integer
10 = x
Rvalue: It is an rvalue expression that is used to store a value in some address of memory.
An rvalue can appear only on the right- hand side because it is a value of the variable that
defines on the right-hand side.
Dim name As String
Name = "Peter" // rvalue define at right side of the assignment operator.
VB.NET CONSTANTS
As the name suggests, the name constant refers to a fixed value that cannot be changed
during the execution of a program. It is also known as literals. These constants can be of any
data type, such as Integer, Double, String, Decimal, Single, character, enum, etc.
Declaration of Constants
In VB.NET, const is a keyword that is used to declare a variable as constant. The Const
statement can be used with module, structure, procedure, form, and class.
Syntax:
Const constname As datatype = value
Further, if we want to declare more than one variable in the same line, we must separate
each variable with a comma, as shown below. The Syntax for defining the multiple variables
as constant is:
Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3 As
DataType3
Note: The statements given below are also used to declare the variable with their data type:
Const num As Integer = 10
Static name As String
Public Const name As String = "VB .Net"
Private Const PI As Double = 3.14
Const1.vb
Module Const1
Sub main()
'declaration and initialization of Constant variable using Const keywords
Const intData As Integer = 20
Const name As String = "WELCOME"
Const topic As String = "VB.NET"
Const PI = 3.14
Dim radius, area As Integer
Console.WriteLine(" Constant integer is {0}", intData)
Console.WriteLine(" You have entered {0}", name)
Console.WriteLine(" Your Topic is {0}", topic)
Console.WriteLine("Enter the Radius")
radius = Console.ReadLine()
area = PI * radius * radius
Console.WriteLine(" Area of Circle is {0}", area)
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 30
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
Console.ReadKey()
End Sub
End Module
Output:
Constant integer is 20
You have entered WELCOME
Your Topic is VB.NET
Enter the Radius
7
Area of Circle is 154
Dim X As Integer
Local variables exist until the procedure in which they are declared is executed. Once a
procedure is executed, the values of its local variables will be lost, and the resources used by
these variables will be released. And when the block is executed again, all the local variables
are rearranged.
Let's create a program that displays the local scope of a variable within a function.
Local_Scope.vb
Imports System
Module Local_scope
Sub Main()
Console.WriteLine(" Scope of local varibale within a function")
local() ' call local() and local() function without any object reference
local2()
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 31
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
Sub local()
Dim X As Integer
' declaration of local variable
X = 50
Console.WriteLine(" Value of Local value X is {0}", X)
End Sub
Sub local2()
Dim X As String
' scope of local variable within a function
X = "VB .NET"
Console.WriteLine(" Value of X is {0}", X)
End Sub
End Module
Output:
Scope of local variable within a function
Value of Local value X is 50
Value of X is VB .NET
press any key to exit...
Module Scope
All existing procedures can easily identify a variable that is declared inside a module sheet is
called a module-level variable. The defined module variable is visible to all procedures
within that module only, but it is not available for other module's procedures. The Dim or
private statement at the top of the first procedure declaration can be declared the module-
level variables. It means that these variables cannot be declared inside any procedure block.
Further, these variables are useful to share information between the procedures in the same
module. And one more thing about the module-level variable is that these variables can
remains existence as long as the module is executed.
' It is the declaration section of the module
Private num As Integer ' A private module-level variable
Dim name As String ' Another private module-level variable
Let's create a program that display the module level variable in VB.NET.
Module_scope.vb
Imports System
Module Module_scope
'module-level variable declaration
Dim x As Integer
Private y As Integer
Private name As String = "VB .NET"
Sub example()
x = 10
y = x + 10
Console.WriteLine(" Value of Y is {0}", y)
End Sub
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 32
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
Sub example2()
Console.WriteLine(" Value of X is {0}", x)
Console.WriteLine(" Value of Y is {0}", y)
Console.WriteLine(" Name is {0}", name)
End Sub
Sub example3()
Dim A As Integer ' local variable or local scope
A=x+y
Console.WriteLine(" Local scope within a function of variable A {0}", A)
End Sub
Sub Main()
Console.WriteLine(" Module scope of variable")
example()
example2()
example3()
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:
Module scope of variable
Value of Y is 20
Value of X is 10
Value of Y is 20
Name is VB .NET
Local scope within a function of variable A 30
Press any key to exit...
Global_scope1.vb
Imports System
Module Global_scope1
'Global declaration of a variable
Public str As String = "Hello, Programmer."
Public topic As String
Public exp As Integer
Sub Main()
Console.WriteLine(" You have passed {0}", str)
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 33
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
End Module
Output:
You have passed Hello, Programmer
Enter the topic name
VB.NET
Topic Name :VB.NET
How many years of experienced in VB.NET?
10
Your Experienced is 10
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.
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.
Example 1: 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
If (num Mod 2 = 0) Then ' if condition is true, print the if statement
Console.WriteLine("It is an even number")
Else 'otherwise, Else statement is executed.
Console.WriteLine("It is an odd 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:
Syntax
If(condition 1)Then
' Executes when condition 1 is true
ElseIf( condition 2)Then
' Executes when condition 2 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.
Example 1: Write a program to show the uses of If... ElseIf statements.
if_elseIf.vb
Module if_elseIf
Sub Main()
Dim var1 As Integer
Now compile and execute the above program by clicking on the Start or F5 button, it shows
the following output:
Syntax
Following is the syntax of the Select Case statement in VB.NET, as follows:
Select Case [variable or expression]
Case value1 'defines the item or value that you want to match.
// Define a statement to execute
Case value2 'defines the item or value that you want to match.
Statement2
Case Else
// define the default statement if none of the condition is true
End Select
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.
Syntax:
Select Case "num"
' code to be executed if num = 1
Case 1
' nested Select case
Select Case n
' code to be executed if n = 5
Case 5
Statement 1
' code to be executed if n = 10
Case 10
Statement 2
' code to be executed if n = 15
Case 15
Statement 3
' code to be executed if n doesn't match with any cases.
Case Else
Statement
' code to be executed if num = 2
Case 2
Statement 2
' code to be executed if num = 3
Case 3
Statement 3
' code to be executed if num doesn't match with any cases.
Case Else
Statement
Module1.vb
Module Module1
Sub Main()
Dim x As Integer = 10, y As Integer = 5
Select Case x
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:
VB.NET DO LOOP
A Loop is used to repeat the same process multiple times until it meets the specified
condition in a program. By using a loop in a program, a programmer can repeat any number
of statements up to the desired number of repetitions. A loop also provides the suitability to a
programmer to repeat the statement in a program according to the requirement. A loop is also
used to reduce the program complexity, easy to understand, and easy to debug.
Types of Loops
There are five types of loops available in VB.NET:
o Do While Loop
DO WHILE LOOP
In VB.NET, Do While loop is used to execute blocks of statements in the program, as long as
the condition remains true. It is similar to the While End Loop, but there is slight difference
between them. The while loop initially checks the defined condition, if the condition
becomes true, the while loop's statement is executed. Whereas in the Do loop, is opposite of
the while loop, it means that it executes the Do statements, and then it checks the condition.
Syntax:
Do
[ Statements to be executed]
Loop While Boolean_expression
// or
Do
[Statement to be executed]
Loop Until Boolean_expression
In the above syntax, the Do keyword followed a block of statements, and While keyword
checks Boolean_expression after the execution of the first Do statement.
Flowchart of Do loop
The above flow chart represents the flow of Do While loop. It is used to control the flow of
statements, such that it executes the statement at least once before checking the While or
Until condition. If the condition is true, the next iteration will be executed till the condition
become false.
Example 1. Write a simple program to print a number from 1 to 10 using the Do While loop
in VB.NET.
Do_loop.vb
Imports System
Module Do_loop
Sub Main()
' Initializatio and Declaration of variable i
Dim i As Integer = 1
Do
' Executes the following Statement
End Module
Now compile and execute the above program by clicking on the Start button, it shows
In the above program, the Do While loop executes the body until the given condition
becomes false. When the condition becomes false the loop will be terminated.
Do_loop.vb
Imports System
Module Do_loop
Sub Main()
' Initialization and Declaration of variable i
Dim i As Integer = 1
Do
' Executes the following Statement
Console.WriteLine(" Value of variable i is : {0}", i)
i = i + 1 'Increment variable i by 1
Loop Until i = 10 ' Define the Until Condition
Output:
In the above program, a Do Until loop is executed their statement until the given
condition Until (i =10) is not meet. When the counter value of the variable i becomes 10, the
defined statement will be false, and the loop will be terminated.
NESTED DO WHILE LOOP STATEMENT
In VB.NET, when we use one Do While loop inside the body of another Do While loop, it is
called Nested Do While loop.
Syntax
Do
Example 2: Write a simple program to use the Do While loop Statement in VB.NET.
Nest_Do_While.vb
Imports System
Module Nest_Do_While
Sub Main()
Output:
In the above example, each iteration of the outer loop also executes the inner loop repeatedly
until the inner condition becomes false. When the condition of the outer loop becomes false,
the execution of the outer and inner loop will be terminated.
Syntax
For variable_name As [ DataType ] = start To end [ Step step ]
[ Statements to be executed ]
Next
Let's understand the For Next loop in detail.
In the above flow chart, the first step is to initialize the variable name with the start value.
And then, the value of the variable will be compared to the end expression or value. If the
condition is true, the control enters the loop body and executes the statements. After that, the
value of a variable will be automatically incremented by the compiler. Upon completion of
each iteration, the current value of a variable will be again compared to the end expression.
If the condition is not true, the controlled exit from the loop.
Example 1. Write a simple program to print the number from 1 to 10 using the For Next
loop.
Number.vb
Imports System
Module Number
Sub Main()
' It is a simple print statement, and 'vbCrLf' is used to jump in the next line.
Console.Write(" The number starts from 1 to 10 " & vbCrLf)
' declare and initialize variable i
Console.ReadKey()
End Sub
End Module
Output:
In the above example, we have initialized an integer variable i with an initial value 1. The For
loop will continuously execute its body until the value of i is smaller or equal to 10. After
each iteration, the value of i is automatically increased with 'Step 1'. If the value of i reached
10, the loop would be terminated and control transfer to the Main() function.
Syntax:
For variable_name As [Data Type] = start To end [ Step step ]
For variable_name As [Data Type] = start To end [ Step step ]
[ inner loop statements ]
Next
Nested_loop.vb
Imports System
Module Nested_loop
Sub Main()
Dim i, j As Integer
For i = 1 To 3
'Outer loop
Console.WriteLine(" Outer loop, i = {0}", i)
'Console.WriteLine(vbCrLf)
'Inner loop
For j = 1 To 4
Console.WriteLine(" Inner loop, j = {0}", j)
Next
Console.WriteLine()
Next
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:
In the above example, at each iteration of the outer loop, the inner loop is repeatedly executed
its entire cycles until the condition is not satisfied.
Syntax:
For Each var_name As [ DataType ] In Collection_Object
[ Statements to be executed]
Next
For Each loop is used to read each element from the collection object or an array. The Data
Type represents the type of the variable, and var_name is the name of the variable to access
elements from the array or collection object so that it can be used in the body of For Each
loop.
The first step is to initialize an array or collection object to execute each element of the array
with the help of variables in For Each loop. A variable is used in For Each loop to checks
whether the element is available or not. If the element is available in the collection object, the
For Each block will be executed until the condition remains true. After the execution of each
element of an array, the control transfer to the end statement.
For_Each_loop.vb
Imports System
Module For_Each_loop
Sub Main()
'declare and initialize an array as integer
Dim An_array() As Integer = {1, 2, 3, 4, 5}
End Sub
End Module
Output:
In the above example, we create an integer array with the name An_array (), and For Each
loop is used to iterate each element of the array with the help of defined variable 'i'.
While [condition]
[ Statement to be executed ]
End While
Here, condition represents any Boolean condition, and if the logical condition is true,
the single or block of statements define inside the body of the while loop is executed.
As we know, the While End loop is an entry-controlled loop used to determine if the
condition is true, the statements defined in the body of the loop are executed, and the
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 54
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
execution process continues till the condition is satisfied. Furthermore, after each iteration,
the value of the counter variable is incremented. It again checks whether the defined
condition is true; And if the condition is again true, the body of the While loop is executed.
And when the condition is not true, the control transferred to the end of the loop.
Example: Write a simple program to print the number from 1 to 10 using while End loop
in VB.NET.
while_number.vb
Imports System
Module while_number
Sub Main()
'declare x as an integer variable
Dim x As Integer
x=1
' Use While End condition
While x <= 10
'If the condition is true, the statement will be executed.
Console.WriteLine(" Number {0}", x)
x = x + 1 ' Statement that change the value of the condition
End While
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:
In the above example, while loop executes its body or statement up to the defined state (i <=
10). And when the value of the variable i is 11, the defined condition will be false; the loop
will be terminated.
Syntax
While (condition -1)
// body of the outer while loop
While (condition -2)
Nest_While.vb
Imports System
Module Nest_While
Sub Main()
' Declare i and j as Integer variable
Dim i As Integer = 1
While i < 4
' Outer loop statement
Console.WriteLine(" Counter value of Outer loop is {0}", i)
Dim j As Integer = 1
While j < 3
'Inner loop statement
Console.WriteLine(" Counter value of Inner loop is {0}", j)
j = j + 1 ' Increment Inner Counter variable by 1
End While
Console.WriteLine() 'print space
i = i + 1 ' Increment Outer Counter variable by 1
End While
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:
In the above example, at each iteration of the outer loop, the inner loop is repeatedly executed
its entire cycles until the inner condition is not satisfied. And when the condition of the outer
loop is false, the execution of the outer and inner loop is terminated.
VB.NET 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.
Declaration of VB.NET Array
We can declare an array by specifying the data of the elements followed by parentheses () in
the VB.NET.
Dim array_name As [Data_Type] ()
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.
Now, let us see the example to declare an array.
Furthermore, we can also initialize and declare an array using the following ways, as shown
below.
Dim intData() As Integer = {1, 2, 3, 4, 5}
Dim intData(5) As Integer
Let's create a program to add the elements of an array in VB.NET programming language.
num_Array.vb
Imports System
Module num_Array
Sub Main()
Dim i As Integer, Sum As Integer = 0
'In VB.NET the size of an array is n+1
'Declaration and Initialization of marks() array
Dim marks() As Integer = {58, 68, 95, 50, 23, 89}
Console.WriteLine(" Marks in 6 Subjects")
For i = 0 To marks.Length - 1
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 58
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET
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
Imports System
Module Input_array
Sub Main()
'Definition of array
Dim arr As Integer() = New Integer(5) {}
For i As Integer = 0 To 5
Console.WriteLine(" Enter the value for arr[{0}] : ", i)
arr(i) = Console.ReadLine() ' Accept the number in array
Next
Console.WriteLine(" The array elements are : ")
' Definition of For loop
For j As Integer = 0 To 5
Console.WriteLine("{0}", arr(j))
Next
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
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.
Dim intArray As Integer( , ) = New Integer( 3, 2) { {4, 5}, {2, 3}, {6, 7} }
Dim intArray( , ) As Integer = { {5, 4}, {3, 2}, {4, 7} }
' Initialization of Three Dimensional Array
Dim threeDimen(3, 3, 2 ) As Integer = { {{1, 3, 2}, {2, 3, 4}}, {{5, 3, 6}, {3, 4, 5}}, {{1,
2, 2}, {5, 2, 3} }}
MultidimenArray.vb
Imports System
Module MultidimenArray
Sub Main()
' Definition of 2 Dimensional Array
Dim intArray(,) As Integer = {{5, 4}, {3, 2}, {4, 7}, {4, 5}}
' Definition of 3 Dimensional Array
Dim threeDimen(,,) As Integer =
{{{1, 3, 2}, {2, 3, 4}},
{{5, 3, 6}, {3, 4, 5}},
{{1, 2, 2}, {5, 2, 3}}}
Console.WriteLine(" Two Dimensional Arraye in VB.NET are")
For i As Integer = 0 To 3
For j As Integer = 0 To 1
Console.WriteLine("intArray[{0}, {1}] = {2}", i, j, intArray(i, j))
Next j
Next i
Console.WriteLine(" Three Dimensional Arraye in VB.NET are")
For i As Integer = 0 To 2 - 1
For j As Integer = 0 To 2 - 1
For k As Integer = 0 To 4
Console.WriteLine("intArray[{0}, {1}, {2}] = {3}", i, j, k, threeDimen(i, j, k))
Next k
Next j
Next i
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:
names(1) = "Henry"
names(2) = "Rock"
names(3) = "James"
names(4) = "John"
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.