0% found this document useful (0 votes)
61 views63 pages

Unit III - Introduction To VB

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

Unit III - Introduction To VB

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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN

C# AND DOT NET


FRAMEWORK
UNIT 3 INTRODUCTION TO VB .NET
KAVITHA RAJALAKSHMI D
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

 It is an object-oriented programming language that follows various oops concepts


such as abstraction, encapsulation, inheritance, and many more. It means that
everything in VB.NET programming will be treated as an object.
 This language is used to design user interfaces for window, mobile, and web-based
applications.
 It supports a rapid application development tool kit. In which a developer does not
need to write all the codes as it can get various code automatically from its libraries.
For example, when we create a form in Visual basic.net, it automatically calls events
of various form in that class.
 It is not a case sensitive language like other languages such as C++, java, etc.
 It supports Boolean condition for decision making in programming.
 It also supports the multithreading concept, in which you can do multiple tasks at the
same time.
 It provides simple events management in .NET application.
 A Window Form enables us to inherit all existing functionality of form that can be
used to create a new form. So, in this way, it reduced the code complexity.
 It uses an external object as a reference that can be used in a VB.NET application.
 Automatic initialized a garbage collection.
 It follows a structured and extensible programming language for error detection and
recovery.
 Conditional compilation and easy to use generic classes.
 It is useful to develop web, window, and mobile applications.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 1


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

 The VB.NET programming language is unable to handle pointers directly. Because in


this language, it requires a lot of programming, and it is not easy to manage every
address by a pointer. Furthermore, additional coding takes extra CPU cycles, that
increases the processing time. It shows the slowness of the VB.NET application.
 The VB.NET programming is easy to learn, that increases a large competition
between the programmers to apply the same employment or project in VB.NET.
Thus, it reduces a secure job in the programming field as a VB.NET developer.
 It uses an Intermediate Language (IL) compilation that can be easily decompiled
(reverse engineered), but there is nothing that can prevent an application from
disintegrating.
 Just-In-Time (JIT) compiler: It is the process through which a computer can interpret
IL (intermediate language) compilation and is also required to run your application. It
means that the target computer needs a JIT compiler to interpret a source program in
IL, and this interpretation requires an additional CPU cycle that degrades the
performance of an application.
 It contains a large collection of libraries for the JIT compiler that helps to interpret an
application. These large libraries hold a vast space in our system that takes more
computing time.

CREATING A SHORTCUT TO START VB .NET


In the following section we are going to create a shortcut for starting the VB.NET (i.e. Visual
Basic .NET). You can start the Visual Basic by choosing Start | All Programs | Microsoft
Visual Studio .NET | Microsoft Visual Studio .NET. But using a shortcut will enable you to
start the Visual Basic more quickly. This shortcut is nothing but an icon that will be placed on
the wallpaper. All you have to do is double click this icon to start the Visual Basic .NET.
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 2
KAVITHA RAJALAKSHMI D INTRODUCTION TO 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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 3


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 4


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

OPENING AND CLOSING WINDOWS AND TOOLBARS


The following windows are most commonly needed while developing Visual Basic .NET
applications: Windows Forms Designer window (or simply, form window), Toolbox,
Solution Explorer, Properties window, Class View window, and Output window. In order to
close any of these windows, simply click the close-window-button of that window. In order
to open any window (except the form window) use the View-menu as follows:
1. In order to open the Toolbox, choose View | Toolbox.
2. In order to open the Solution Explorer, choose View | Solution Explorer.
3. In order to open the Properties window, choose View | Properties Window.
4. In order to open the Class View window, choose View | Class View.
5. In order to open the Output window, choose View | Other Windows | Output.
6. Similarly, try other menu options in the View-menu to open the various windows.
In order to open the form window, follow these steps:

 Open the Solution Explorer.


 See to it that the form icon is displayed in the Solution Explorer. Click the + sign
shown in Figure 3.6 (a) and then the form icon appears as shown in Figure 3.6 (b).
 Double-click the form icon—shown in Figure 3.6 (b) and the form window appears
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:

Build Crystal Reports-Insert Crystal Reports-Main


Data Design Database Diagram Debug
Debug Location Design Dialog Editor
Formatting Full Screen HTML Editor
Image Editor Layout Query
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 5
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

Source Control Standard Style Sheet


Table Text Editor View
Web XML Data XML Schema

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.

USING THE AUTO HIDE FACILITY


The Auto Hide facility is a new addition to the Visual Basic .NET program. This facility was
not available in Visual Basic 6. This facility allows us to hide the windows when not needed
and call them back when they are. Let us learn how to use this facility. Click the Toolbox tab
as shown in Figure 3.8, and the Toolbox slides on the screen as shown in Figure 3.9. The
Toolbox overlaps the form window. Now you can use the Toolbox and when you want to
hide it, simply click somewhere on the form window (but not on the Toolbox) as shown in
Figure 3.9, and the Toolbox slides off the screen.
We can use the Auto Hide facility only if the Auto Hide tool is enabled. The Auto Hide tool
is placed close to the close-window-button on the various windows, such as, Toolbox,
Properties window, Solution Explorer, and other windows. The Auto Hide tool is a toggle
switch and every time you click it, it toggles between the “Auto Hide enabled” and “Auto
Hide disabled” states. Figure 3.10 shows the Auto Hide tool in both states. If the Auto Hide
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 6
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 7


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

DOCKING AND UNDOCKING THE WINDOWS


If the Auto Hide facility of a window is enabled then it always remains docked; you cannot
convert such windows into an undocked (or floating) one. A dockable window is that which
exhibits a sort of magnetic effect with the edges of the main window. When a dockable
window is taken close to the edge of the main window then it simply sticks (or gets docked)
to the edge of the main window. Notice the following points in this regard:
Only a docked window displays the Auto Hide tool on its title bar. An undocked window (or
floating window) doesn’t display the Auto Hide tool on its title bar (see Figure 3.11).
If you double-click the titlebar of a docked window (with Auto Hide facility enabled) then
nothing happens.

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.

PLACING A WINDOW AT A SUITABLE LOCATION


A window with Auto Hide facility enabled cannot be moved or relocated on the screen.
However, you can move or relocate a window with Auto Hide facility disabled. The
procedure of moving or relocating a window in Visual Studio .NET is the same as that of
Windows XP.

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

Figure 3.12 Windows Form Application

Finally, select OK, Microsoft Visual Studio creates your project and displays following
window Form with a name Form1.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 9


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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 −

Figure 3.13 VB .NET Form

VB.Net Form Title Bar


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

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

S.N Properties Description

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


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

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

This Boolean property determines whether the controls you


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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 10


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

This Boolean property indicates whether scroll bars will be


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

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

The AutoScrollPosition is the number of pixels by which the


6 AutoScrollPosition
two scroll bars were displaced from their initial locations.

7 BackColor Sets the form background color.

The BorderStyle property determines the style of the form's


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

 SizableToolWindow − Same as the FixedToolWindow


but resizable. In addition, its caption font is smaller
than the usual.

By default, this property is True and you can set it to False to


9 ControlBox
hide the icon and disable the Control menu.

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


10 Enabled
events; if False, disables form.

11 Font This property specify font type, style, size

Determines whether a Help button should be displayed in the


12 HelpButton
caption box of the form.

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

By default, this property is True and you can set it to False to


14 MinimizeBox
hide the Minimize button on the title bar.

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

hide the Maximize button on the title bar.

This specifies the minimum height and width of the window


16 MinimumSize
you can minimize.

This specifies the maximum height and width of the window


17 MaximumSize
you maximize.

18 Name This is the actual name of the form.

This property determines the initial position of the form when


it's first displayed. It will have any of the following values −
 CenterParent − The form is centered in the area of its
parent form.
 CenterScreen − The form is centered on the monitor.

19 StartPosition  Manual − The location and size of the form will


determine its starting position.
 WindowsDefaultBounds − The form is positioned at
the default location and size determined by Windows.
 WindowsDefaultLocation − The form is positioned at
the Windows default location and has the dimensions
you've set at design time.

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

These two properties set or return the coordinates of the form's


21 Top, Left
top-left corner in pixels.

This property is a True/False value that lets you specify


22 TopMost whether the form will remain on top of all other forms in your
application. Its default property is False.

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

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

r.No. Method Name & Description

1 Activate - Activates the form and gives it focus.

2 ActivateMdiChild - Activates the MDI child of a form.

3 AddOwnedForm - Adds an owned form to this form.

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

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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 12


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

6 CenterToScreen - Centers the form on the current screen.

7 Close - Closes the form.

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

9 Focus - Sets input focus to the control.

10 Hide - Conceals the control from the user.

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.

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

14 ScaleCore - Performs scaling of the form.

15 Select - Activates the control.

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

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

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

19 SetDesktopLocation - Sets the location of the form in desktop coordinates.

20 SetDisplayRectLocation - Positions the display window to the specified value.

21 Show - Displays the control to the user.

22 ShowDialog -Shows the form as a modal dialog box.

Form Events
Following table lists down various important events related to a form. You can refer to
Microsoft documentation for a complete list of events associated with forms control −

Sr.No. Event Description

1 Activated Occurs when the form is activated in code or by the user.

2 Click Occurs when the form is clicked.

3 Closed Occurs before the form is closed.

4 Closing Occurs when the form is closing.

5 DoubleClick Occurs when the form control is double-clicked.

6 DragDrop Occurs when a drag-and-drop operation is completed.

7 Enter Occurs when the form is entered.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 13


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

8 GotFocus Occurs when the form control receives focus.

9 HelpButtonClicked Occurs when the Help button is clicked.

10 KeyDown Occurs when a key is pressed while the form has focus.

11 KeyPress Occurs when a key is pressed while the form has focus.

12 KeyUp Occurs when a key is released while the form has focus.

13 Load Occurs before a form is displayed for the first time.

14 LostFocus Occurs when the form loses focus.

Occurs when the mouse pointer is over the form and a mouse
15 MouseDown
button is pressed.

16 MouseEnter Occurs when the mouse pointer enters the form.

17 MouseHover Occurs when the mouse pointer rests on the form.

18 MouseLeave Occurs when the mouse pointer leaves the form.

19 MouseMove Occurs when the mouse pointer is moved over the form.

Occurs when the mouse pointer is over the form and a mouse
20 MouseUp
button is released.

Occurs when the mouse wheel moves while the control has
21 MouseWheel
focus.

22 Move Occurs when the form is moved.

23 Resize Occurs when the control is resized.

24 Scroll Occurs when the user or code scrolls through the client area.

25 Shown Occurs whenever the form is first displayed.

26 VisibleChanged Occurs when the Visible property value changes.

Example
Following is an example, which shows how we create two buttons at the time of form load
event and different properties are being set at the same time.
Because Form1 is being referenced within its own event handler, so it will be written as Me
instead of using its name, but if we access the same form inside any other control's event
handler, then it will be accessed using its name Form1.
Let's double click on the Form and put the follow code in the opened window.

Public Class Form1


Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Create two buttons to use as the accept and cancel buttons.
Dim button1 As New Button()
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 14
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

Dim button2 As New Button()


' Set the text of button1 to "OK".
button1.Text = "OK"
' Set the position of the button on the form.
button1.Location = New Point(10, 10)
' Set the text of button2 to "Cancel".
button2.Text = "Cancel"
' Set the position of the button based on the location of button1.
button2.Location = _
New Point(button1.Left, button1.Height + button1.Top + 10)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
' Display a help button on the form.
Me.HelpButton = True
' Define the border style of the form to a dialog box.
Me.FormBorderStyle = FormBorderStyle.FixedDialog
' Set the MaximizeBox to false to remove the maximize box.
Me.MaximizeBox = False
' Set the MinimizeBox to false to remove the minimize box.
Me.MinimizeBox = False
' Set the accept button of the form to button1.
Me.AcceptButton = button1
' Set the cancel button of the form to button2.
Me.CancelButton = button2
' Set the start position of the form to the center of the screen.
Me.StartPosition = FormStartPosition.CenterScreen
' Set window width and height
Me.Height = 300
Me.Width = 560
' Add button1 to the form.
Me.Controls.Add(button1)
' Add button2 to the form.
Me.Controls.Add(button2)
End Sub
End Class

When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window –

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 15


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

Figure 3.14 VB. Net Toolbox

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.

SOLUTION EXPLORER WINDOW


The Solution Explorer window contains a list of the items in the current solution. A solution
can contain multiple projects, and each project can contain multiple items. The Solution
Explorer displays a hierarchical list of all the components, organized by project. You can
right-click any component of the project and choose Properties in the context menu to see the
selected component’s properties in the Properties window. If you select a project, you will
see the Project Properties dialog box. You will find more information on project properties in
the following chapter.

Figure 3.15 VB. Net Solution Explorer Window

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 16


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 17


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

WRITING AN EVENT PROCEDURE


A procedure is nothing but a piece of Visual Basic program. Event procedure is a piece of
program that responds to a particular event. As you know, a program is also known as a code.
This code needs to be written in the code window. The code window can be opened by using
one of the methods given below:
Double-click the object for which you intend to write an event procedure and Visual Basic
opens the code window for you (Figure 3.17). Visual Basic also writes wrapper lines for you
and places the keyboard-cursor between these wrapper lines.
Click the object for which you intend to write an event procedure. Choose View | Code (or
strike the function key F7), and Visual Basic opens the code window for you (Figure 3.17).

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 18


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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:

Private Sub btnExit_Click ( list_of_arguments) Handles btnExit.Click


End
End Sub
Click the Save All tool on the Standard toolbar. This event procedure consists of three lines
of code. Let us discuss these three lines in detail.
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 19
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 20


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

EXECUTING THE HELLO PROJECT USING EXPLORER


Now let us execute the stand alone version of Hello project by using the Windows Explorer.
Follow these steps:
Choose Start | All Programs | Accessories | Windows Explorer, and Windows Explorer pops
up on the screen.
Type the following text in the edit-box (actually it is combo-box) Address:

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.

Click the button Exit, and the application terminate

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.

ddHandler AddressOf Alias And AndAlso As

Boolean ByRef Byte ByVal Call Case

Catch CBool CByte CChar CDate CDbl

CDec Char Cint Class CLng CObj

Const Continue CSByte CShort CSng CStr

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 21


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

CType CUnit CULng CUShort Date Decimal

Declare Default Delegate Dim DirectCast Do

Double Each Else Elseif End End if

Enum Erase Error Event Exit False

Finally For Friend Function Get GetType

GetXML
Global GoTO Handles If Implements
Namespace

Imports In Inherits Integer Interface Is

isNot Let Lib Like Long Loop

Me Mod Module MustInherit MustOverride MyBase

MyClass Namespace Narrowing New Next Not

Not Not
Nothing Object Of On
Inheritable Overridable

Operator Option Optional Or OrElse Overloads

Overridable Overrides ParamArray Partial Private Property

Protected Public RaiseEvent ReadOnly ReDim REM

Remove Handler Resume Return SByte Select Set

Shadows Shared Short Single Static Step

Stop String Structure Sub SyncLock Then

Throw To True Try TryCast TypeOf

UInteger While Widening With WithEvents WhiteOnly

Xor #Else IsReference TimeOfDay Append Auto

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 22


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

 It should not more than 51 characters.


 An identifier can contain two underscores, but should not be consecutive.
 It should not include any commas or white spaces in-between characters.
Generally, identifiers are meaningful names. Some valid identifiers are:
Value, a, rec1, my_data, Marks, num, etc.
Some invalid identifiers are:
5be : First character should be alphabets or underscore (_)

Class, Shared : Keyword are not allowed as identifier name.


A# - : Identifier does not contain any special symbol.
Avg marks : It should not contain any blank space.

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.

In VB.NET, we use ( ' ) symbol to comment a statement.


Sub main()
'Here Console.WriteLine() is used to print a statement.
Console.WriteLine(" Welcome to JavaTpoint")
'Above statement displays Welcome to JavaTpoint
End Sub

VB.NET DATA TYPE


In VB.NET, data type is used to define the type of a variable or function in a program.
Furthermore, the conversion of one data type to another type using the data conversion
function.
A Data Type refers to which type of data or value is assigning to a variable or function so
that a variable can hold a defined data type value. For example, when we declare a variable,
we have to tell the compiler what type of data or value is allocated to different kinds of
variables to hold different amounts of space in computer memory.

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

Different Data Types and their allocating spaces in VB.NET


The following table shows the various data types list in the VB.NET programming language.

Data Types Required Space Value Range

A Boolean type depends


Boolean on the implementing True or False
platform

Byte 1 byte Byte Range start from 0 to 255 (unsigned)

Char 2 bytes Char Range start from 0 to 65535 (unsigned)

Date range can be 0:00:0 (midnight) January 1,


Date 8 bytes
0001 to 11:5959 PM of December 31, 9999.

Range from 0 to +/-


79,228,162,514,264,337,593,543,950,335
Decimal 16 bytes (+/-7.9…E+28) without any decimal point;
And 0 to +/-7.92281625142264337593543950335
with 28 position to the right of the decimal

-1.79769313486231570E+308 to -4.94-
65645841246544E-324 for negative values;
Double 8 bytes
4.94065645841246544E-324 to
1.79769313486231570E+308, for positive values

Integer 4 bytes -2,147,483,648 to 2,147,483,647 (signed)

-9,223,372,036,854,775,808 to
Long 8 bytes
9,223,372,036,854,775,807 (9.2…E + 18) (signed)

Object size based on the


platform such as 4 bytes It can store any type of data defined in a variable
Object
in 32-bit and 8 bytes in of type Object
64-bit platform

SByte 1 byte -128 to 127 (signed)

Short 2 bytes -32,768 to 32,767 (signed)

-3.4028235E + 38 to -1.401298E-45 for negative


values;
Single 4 bytes
And for positive value: 1.401298E-45 to
3.4028235E + 38.

String Datatype depend


It accepts Unicode character from 0 to
String on the implementing
approximately 2 billion characters.
platform

The range start from 0 to 4,294,967,295


UInteger 4 bytes
(unsigned)

ULong 8 bytes The range of ULong start from 0 to


18,446,744,073,709,551,615 (1.8…E + 19)
GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 24
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

UShort 2 bytes Range from 0 to 65,535 (unsigned)

TYPE CONVERSION FUNCTIONS IN VB.NET


The following functions are available for conversion.
1. CBool(expression): It is used to convert an expression into a Boolean data type.
2. CByte(expression): It is used to convert an expression to a Byte data type.

3. CChar(expression): It is used to convert an expression to a Char data type.


4. CDate(expression): It is used to convert an expression to a Date data type.
5. CDbl(expression): It is used to convert an expression into a Double data type.
6. CDec(expression): It is used to convert an expression into a Decimal data type.
7. CInt(expression): It is used to convert an expression to an Integer data type.
8. CLng(expression): It is used to convert an expression to a Long data type.

9. CObj(expression): It is used to convert an expression to an Object data type.


10. CSByte(expression): It is used to convert an expression to an SByte data type.
11. CShort(expression): It is used to convert an expression to a Short data type.
12. CSng(expression): It is used to convert an expression into a Single data type.
13. CStr(expression): It is used to convert an expression into a String data type.
14. CUInt(expression): It is used to convert an expression to a UInt data type.

15. CULng(expression): It is used to convert an expression to a ULng data type.


16. CUShort(expression): It is used to convert an expression into a UShort data type.

VB.NET VARIABLE AND CONSTANT


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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 25


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

VB.NET Variables Declaration


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

Syntax:
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

Dim Emp_id, Stud_id As Integer


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

Syntax
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:

Static name As String


Public bill As Decimal = 0

VB.NET Variable Initialization


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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 26


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

Syntax:
Variable_name = value

For example:
Dim Roll_no As Integer 'declaration of Roll_no

Roll_no = 101 'initialization of Roll_no


Initialize the Emp_name
Dim Emp_name As String
Emp_name = "David" 'Here Emp_name variable assigned a value of David
Initialize a Boolean variable
Dim status As Boolean 'Boolean value can be True or False.

status = True 'Initialize status value to True


We can also initialize a variable at the time of declaration:
Dim Roll_no As Integer = 101
Dim Emp_name As String = " Stephen Robert "
Let's create a program to use different types of variable declaration and initialization in
VB.NET.

Variable1.vb
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

Console.WriteLine(" Value of CharData is: {0}", CharData)


Console.WriteLine(" Value of strData is: {0}", strData)
Console.WriteLine(" Value of dblData is: {0}", dblData)
Console.WriteLine(" Value of single_data is: {0}", single_data)
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:
Value of intData is: 10
Value of CharData is: A
Value of strData is: VB.NET is a Programming Language.
Value of dblData is: 4567.676
Value of single_data is: 23.08
press any key to exit...

Getting Values from the User in VB.NET


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

Dim name As String


name = Console.ReadLine()
Or name = Console.ReadLine
Let's create a program that takes input from the user.

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

Enter Your Good name


Alexander
Enter your Age
27.5
You have entered 7
You have entered Alexander
You have entered 27.5

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

Lvalues and Rvalues in VB.NET


There are two ways to express the expression value:
Lvalue: It is an lvalue expression that refers to a memory location for storing the address of a
variable. An lvalue is a variable that can appear to the left or right of the assignment operator
to hold values. Furthermore, in comparison to or swapping the variables' values, we can also
define the variable on both sides (left or right-side) of the assignment operator.

Example:
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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 29


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

Item Name Descriptions


Const It is a Const keyword to declare a variable as constant.
Constname It defines the name of the constant 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 as constant.

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

Example of Const keyword

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

SCOPE OF VARIABLE IN VB.NET


The scope of a variable determines the accessible range of a defined variable at the time of
declaration in any block, module, and class. You can access it if the variable is in a particular
region or scope in the same block. And if the variable goes beyond the region, its scope
expires.
The following are the methods to represent the scope of a variable in VB.NET.
1. Procedure Scope
2. Module Scope
3. Public Scope

Procedure (local) scope


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

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 (Public) Scope


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

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

Global_scope1.vb

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

Console.WriteLine(" Enter the topic name")


topic = Console.ReadLine
Console.WriteLine(" Topic Name :{0}", topic)
Console.WriteLine("How many years of experienced in {0}?", topic)
exp = Console.ReadLine
Console.WriteLine(" Your Experienced is {0} ", exp)
Console.ReadKey()
End Sub

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

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:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 34


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

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


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

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

Syntax:
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:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 35


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 36


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

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

If_Else_statment.vb
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:

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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 37


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

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

ElseIf var1 >= 100 Then


GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 38
KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

Console.WriteLine(" Entered value is greater than 100")


Else
'if none of the above condition is satisfied, print the following statement
Console.WriteLine(" Value is not matched with above condition")
End If
Console.WriteLine(" You have entered : {0}", var1)
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
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.

// 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:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 39


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

Select Case Variable / expression


Case value1
Statement1
Case value2, value3

Statement2
Case Else
// define the default statement if none of the condition is true
End Select

Flowchart of Select Case Statement


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

In Flowchart, the Select Case statement represents the evaluating of the process start from top
to bottom. If the expression or value is matched with the first select case, statement -1 is
executed else the control transfer to the next case for checking whether the expression is
matching or not. Similarly, it checks all Select case statements for evaluating. If none of the
cases are matched, the Else block statement will be executed, and finally, the Select Case
Statement will come to an end.
Example 1: Write a program to display the Days name using the select case statement in
VB.NET.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 40


KAVITHA RAJALAKSHMI D INTRODUCTION TO 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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 41


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

VB.NET NESTED SELECT CASE STATEMENTS


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

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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 42


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

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:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 43


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

VB.NET DO LOOP
A Loop is used to repeat the same process multiple times until it meets the specified
condition in a program. By using a loop in a program, a programmer can repeat any number
of statements up to the desired number of repetitions. A loop also provides the suitability to a
programmer to repeat the statement in a program according to the requirement. A loop is also
used to reduce the program complexity, easy to understand, and easy to debug.

Advantages of VB.NET loop


o It provides code iteration functionality in a program.

o It executes the statement until the specified condition is true.


o It helps in reducing the size of the code.
o It reduces compile time.

Types of Loops
There are five types of loops available in VB.NET:
o Do While Loop

o For Next Loop


o For Each Loop
o While End Loop
o With End Loop

DO WHILE LOOP
In VB.NET, Do While loop is used to execute blocks of statements in the program, as long as
the condition remains true. It is similar to the While End Loop, but there is slight difference
between them. The while loop initially checks the defined condition, if the condition
becomes true, the while loop's statement is executed. Whereas in the Do loop, is opposite of
the while loop, it means that it executes the Do statements, and then it checks the condition.

Syntax:
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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 44


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

Console.WriteLine(" Value of variable I is : {0}", i)


i = i + 1 'Increment the variable i by 1
Loop While i <= 10 ' Define the While Condition
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 button, it shows

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 45


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

the following output:

In the above program, the Do While loop executes the body until the given condition
becomes false. When the condition becomes false the loop will be terminated.

Use of Until in Do Until Loop statement


In the VB.NET loop, there is a Do Until loop statement, which is similar to the Do While
loop. The Do Statement executes as long as Until condition becomes true.
Example: Write a program to understand the uses of Do Until Loop in VB.NET.

Do_loop.vb

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

Console.WriteLine(" Press any key to exit...")


Console.ReadKey()
End Sub
End Module

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 46


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

// Statement of the outer loop


Do
// Statement of outer loop
While (condition -2)
// Statement of outer loop
While (condition -1)

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

' Declare i and j as Integer variable


Dim i As Integer = 1
Do
' Outer loop statement

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 47


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

Console.WriteLine(" Execution of Outer loop is {0}", i & " times")


Dim j As Integer = 1
Do

'Inner loop statement


Console.WriteLine(" Execution of Inner loop is {0}", j)
j = j + 1 ' Increment Inner Counter variable by 1
Loop While j < 3
Console.WriteLine()
i = i + 1 ' Increment Outer Counter variable by 1

Loop While i < 4


Console.WriteLine(" Exit from the loop")
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module

Output:

In the above example, each iteration of the outer loop also executes the inner loop repeatedly
until the inner condition becomes false. When the condition of the outer loop becomes false,
the execution of the outer and inner loop will be terminated.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 48


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

FOR NEXT LOOP


A For Next loop is used to repeatedly execute a sequence of code or a block of code until a
given condition is satisfied. A For loop is useful in such a case when we know how many
times a block of code has to be executed. In VB.NET, the For loop is also known as For Next
Loop.

Syntax
For variable_name As [ DataType ] = start To end [ Step step ]
[ Statements to be executed ]
Next
Let's understand the For Next loop in detail.

o For: It is the keyword that is present at the beginning of the definition.


o variable_name: It is a variable name, which is required in the For loop Statement.
The value of the variable determines when to exit from the For-Next loop, and the
value should only be a numeric.
o [Data Type]: It represents the Data Type of the variable_name.
o start To end: The start and end are the two important parameters representing the
initial and final values of the variable_name. These parameters are helpful while the
execution begins, the initial value of the variable is set by the start. Before the
completion of each repetition, the variable's current value is compared with the end
value. And if the value of the variable is less than the end value, the execution
continues until the variable's current value is greater than the end value. And if the
value is exceeded, the loop is terminated.
o Step: A step parameter is used to determine by which the counter value of a variable
is increased or decreased after each iteration in a program. If the counter value is not
specified; It uses 1 as the default value.
o Statements: A statement can be a single statement or group of statements that execute
during the completion of each iteration in a loop.
o Next: In VB.NET a Next is a keyword that represents the end of the For loop's
Flowchart of For Next loop

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 49


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

For i As Integer = 1 To 10 Step 1


' if the condition is true, the following statement will be executed
Console.WriteLine(" Number is {0} ", i)
' after completion of each iteration, next will update the variable counter
Next
Console.WriteLine(" Press any key to exit... ")

Console.ReadKey()
End Sub
End Module

Output:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 50


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

NESTED FOR NEXT LOOP IN VB.NET


In VB.NET, when we write one For loop inside the body of another For Next loop, it is
called Nested For Next loop.

Syntax:
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

[ Outer loop statements ]


Next
Following is the example of Nested For Next loop in VB.NET.

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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 51


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

VB.NET FOR EACH LOOP


In the VB.NET, For Each loop is used to iterate block of statements in an array or collection
objects. Using For Each loop, we can easily work with collection objects such as lists, arrays,
etc., to execute each element of an array or in a collection. And when iteration through each
element in the array or collection is complete, the control transferred to the next statement to
end the loop.

Syntax:
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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 52


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

Examples of For Each Loop


Write a simple program to understand the uses of For Each Next loop in VB.NET.

For_Each_loop.vb

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}

Dim i As Integer 'Declare i as Integer


For Each i In An_array
Console.WriteLine(" Value of i is {0}", i)
Next
Console.WriteLine("Press any key to exit...")
Console.ReadLine()

End Sub
End Module

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 53


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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

VB.NET WHILE END LOOP


The While End loop is used to execute blocks of code or statements in a program, as long as
the given condition is true. It is useful when the number of executions of a block is not
known. It is also known as an entry-controlled loop statement, which means it initially
checks all loop conditions. If the condition is true, the body of the while loop is executed.
This process of repeated execution of the body continues until the condition is not false. And
if the condition is false, control is transferred out of the loop.
Syntax:

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.

Flow Diagram of the While End Loop in VB.NET

As we know, the While End loop is an entry-controlled loop used to determine if the
condition is true, the statements defined in the body of the loop are executed, and the
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.

NESTED WHILE END LOOP


In VB.NET, when we write a While End loop inside the body of another While End loop, it is
called Nested While End loop.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 55


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

Syntax
While (condition -1)
// body of the outer while loop
While (condition -2)

// body of inner while loop


End While
// body of the outer loop
End While
Write a program to understand the Nested While End loop in VB.NET programming.

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:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 56


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

'Store only Integer values


Dim num As Integer() or Dim num(5) As Integer
'Store only String values
Dim name As String() or Dim name(5) As String

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 57


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

' Store only Double values


Dim marks As Double()

Initialization of VB.NET Array


In VB.NET, we can initialize an array with New keyword at the time of declaration. For
example,
'Declaration and Initialization of an array elements with size 6
Dim num As Integer() = New Integer(5) { }

Dim num As Integer() = New Integer(5) {1, 2, 3, 4, 5, 6}


Initialize an array with 5 elements that indicates the size of an array
Dim arr_name As Integer() = New Integer() {5, 10, 5, 20, 15}
Declare an array
Dim array1 As Char()
array1 = New Char() {'A', 'B', 'C', 'D', 'E'}

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

Dim array_name() As String = {"Peter", "John", "Brock", "James", "Maria"}


Dim misc() as Object = {"Hello friends", 16c, 12ui, "A"c}
Dim Emp(0 to 2) As String
Emp{0} = "Mathew"
Emp(1) = " Anthony"
Emp(2) = "Prince"

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

Console.WriteLine(" Marks {0}", marks(i))


Sum = Sum + marks(i)
Next
Console.WriteLine(" Grand total is {0}", Sum)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
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 number in VB.NET Array


Let's create a program to take input values from the user and display them in VB.NET
programming language.

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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 59


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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.

Declaration of Multidimensional Array


Declaration of two-dimensional array
Dim twoDimenArray As Integer( , ) = New Integer(3, 2) {}
Or Dim arr(5, 3) As Integer
Representation of Three Dimensional array
Dim arrThree(2, 4, 3) As Integer

Or Dim arr1 As Integer( , , ) = New Integer(5, 5, 5) { }

In the above representation of multidimensional, we have created 2-dimensional


array twoDimenArray with 3 rows and 2 columns and 3-dimensional array with three
dimensions 2, 4, and 3.

Initialization of Multidimensional Array


The following ways to initialize the multidimensional array:
' Initialization of Two Dimensional Array

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

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 60


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

Multidimensional Array Example


Let's create a program to understand the multidimensional array.

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:

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 61


KAVITHA RAJALAKSHMI D INTRODUCTION TO VB .NET

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,
Dim names( 0 to 4) As String
names(0) = "Robert"

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.

GOODWILL CHRISTIAN COLLEGE FOR WOMEN Page 62

You might also like