Unit 1,2&3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

VB.

Net Programming

UNIT I: Introduction .NET Framework


Microsoft .NET Framework is a complex technology that provides the infrastructure for
building, running, and managing next generation applications. In a layered
representation, the .NET Framework is a layer positioned between the Microsoft
Windows operating system and your applications. .NET is a platform but also is defined
as a technology because it is composed of several parts such as libraries, executable
tools, and relationships and integrates with the operating system. Microsoft Visual
Studio 2010 relies on the new version of the .NET Framework 4.0. Visual Basic 2010,
C# 4.0, and F# 2010 are .NET languages that rely on and can build applications for the
.NET Framework 4.0.

The .Net Framework Architecture


The .Net framework is a revolutionary platform that helps you to write the following
types of applications:
 Windows applications
 Web applications
 Web services
The .Net framework applications are multi-platform applications. The framework has
been designed in such a way that it can be used from any of the following languages:
Visual Basic, C#, C++, Jscript, and COBOL, etc. All these languages can access the
framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client
languages like VB.Net. These languages use object-oriented methodology.
Following are some of the components of the .Net framework:
 Common Language Runtime (CLR)
 The .Net Framework Class Library
 Common Language Specification
 Common Type System
 Metadata and Assemblies
 Windows Forms
 ASP.Net and ASP.Net AJAX
 ADO.Net
 Windows Workflow Foundation (WF)
 Windows Presentation Foundation
 Windows Communication Foundation (WCF)

SHASHI RAJ, BMSCW /Page 1


VB.Net Programming

(1) Common Language Runtime or CLR: It performs memory management, exception


handling, debugging, security checking, thread execution, code execution, code safety,
verification, and compilation. The code that is directly managed by the CLR is called the
managed code. When the managed code is compiled, the compiler converts the source
code into a CPU independent intermediate language (IL) code. A Just In Time(JIT)
compiler compiles the IL code into native code, which is CPU specific.
(2) .Net Framework Class Library: It contains a huge library of reusable types.
Classes, interfaces, structures, and enumerated values, which are collectively called
types.
(3) Common Language Specification: It contains the specifications for the .Net
supported languages and implementation of language integration.
(4) Common Type System:It provides guidelines for declaring, using, and managing
types at runtime, and cross-language communication.
(5) Metadata and Assemblies: Metadata is the binary information describing the
program, which is either stored in a portable executable file (PE) or in the memory.
Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code,
and a set of resources like image files.
(6) Windows Forms:Windows Forms contain the graphical representation of any
window displayed in the application.
(7) ASP.NET and ASP.NET AJAX:ASP.NET is the web development model and
AJAX is an extension of ASP.NET for developing and implementing AJAX
functionality. ASP.NET AJAX contains the components that allow the developer to
update data on a website without a complete reload of the page.
(8) ADO.NET:It is the technology used for working with data and databases. It provides
access to data sources like SQL server, OLE DB, XML etc. The ADO.NET allows
connection to data sources for retrieving, manipulating, and updating data.
(9) Windows Workflow Foundation (WF):It helps in building workflow-based
applications in Windows. It contains activities, workflow runtime, workflow designer,
and a rules engine.
SHASHI RAJ, BMSCW /Page 2
VB.Net Programming

(10) Windows Presentation Foundation:It provides a separation between the user


interface and the business logic. It helps in developing visually stunning interfaces using
documents, media, two and three dimensional graphics, animations, and more.
(11) Windows Communication Foundation (WCF):It is the technology used for
building and executing connected systems.

Need for .Net

.NET is a programming framework created by Microsoft that developers can use to


create applications more easily. A “.net framework is just a bunch of code that the
programmer can call without having to write it explicitly."

In a perfect world, you wouldn't need .NET Framework. The makers of all your crucial
applications would have the time and resources to fully patch together their applications
into self-contained packages, because developing for Windows would be an intuitive,
mostly high-level process that independent developers could nail down in fairly quick
order. So nobody besides developers would need a package like .NET, which provides
applications with an orderly way to access databases, web services, and other
communication tools.

One problem .NET installations often run into is a need for space, even if your system
might not make that explicit. The 4.0 version of .NET for standard 32-bit Windows
systems requires 850 MB of free space on your primary Windows drive; a 64-bit
Windows system needs 2 GB free, and Windows usually won't ask you if you have space
on another partition to spare. If your free space is smaller than these amounts, you'll need
to look at your hard drive and free up some space.

Another common problem involves older versions of .NET and, perhaps, their
misbehavior on your system. Head into your Add/Remove Programs section in Control
Panel (or "Uninstall Programs" in newer Windows setups) and search for any
installations related to ".NET Framework," or something very similar. Try removing
them from here, through the standard uninstall procedure, and then try installing your
newer .NET framework again. If that still fails, it's time to turn to the .NET Framework
Cleanup Tool, which was made by Microsoft itself to tidy up and set things straight
following tricky .NET installations.

SHASHI RAJ, BMSCW /Page 3


VB.Net Programming

Layered Design and the Data Access Layer

Layered application designs are extremely popular because they increase application
performance, scalability, flexibility and code reuse. In the classic three tier design,
applications break down into three major areas of functionality:

 The data layer manages the physical storage and retrieval of data
 The business layer maintains business rules and logic
 The presentation layer houses the user interface and related presentation code.

Inside each of these tiers there may also exist a series of sub-layers that provide an even
more granular break up the functional areas of the application. Figure outlines a basic
three tired architecture in ASP.NET along with some of the sub-tiers that you may
encounter:

SHASHI RAJ, BMSCW /Page 4


VB.Net Programming

1.) Presentation Layer(UI) :-


Presentation Layer is nothing but it is a user interface which every user see on your computer
,mobile and window screen. You can say, designing part of any application is known as
Presentation Layer. The User can post input and get output on your presentation Layer only.
2.) Business Access Layer(BAL) :-
Business Access Layer is act as mediator Layer between Presentation layer and Data Access
layer.This layer is used to transfer the data between Presentation Layer and Data Access Layer.
This layer is mainly used for Validations and calculations purpose.
Every validations and calculations of data are held on that layer only.

3.) Data Access Layer (DAL):-

This Layer only communicates with Business Access Layer. Data Access Layer contains the method
that helps Business Access Layer. Business layer class's methods call the Data Access Layer Class
methods to perform some required action with database such as insertion, deletion, updation etc.
All database related connection codes are written in this layer only such as sql query, stored
procedure etc.

OVERVIEW OF THE .NET FRAMEWORK


When Windows 3.0 was introduced, the initial method used for communicating
across applications was Dynamic Data Exchange, or DDE. DDE was resource intensive,
inflexible, and prone to cause system crashes. Nonetheless, it worked acceptably on
single machines, and for many years, many applications continued to use this approach
to send messages between applications. Over the years, Microsoft discouraged the use of
DDE, and encouraged the use of the Common Object Model (COM) and Distributed
COM (DCOM). COM was used for communication among Microsoft applications on a
single machine, whereas DCOM was used to communicate with remote hosts.
Meanwhile, a consortium of allied vendors (including IBM, Sun, and Apple) were
proposing an alternative approach to interhost communication called (Common Object
Request Broker Architecture )CORBA. Unlike COM, CORBA was much better at
passing Messages across different operating systems. Unfortunately, the protocol was
resource-intensive and difficult to program, and its use never lived up to its promise.

During this time, Microsoft was improving its technology, and they introduced
COM+, Microsoft Transaction Server (MTS), and Distributed Network Architecture
(DNA).These technologies allowed more sophisticated interactions among components,
such as object pooling, events, and transactions.

Unfortunately, these technologies required that each of the applications know a


great deal about the other applications, and so they didn’t work very well when the
operating platforms were heterogeneous (for example, Windows apps communicating
with Linux). This brings us to the year 2001 and the .NET initiative, which combines the
power of COM with the flexibility of CORBA. Although this technology is primarily

SHASHI RAJ, BMSCW /Page 5


VB.Net Programming

associated with Microsoft, its flexibility and scalability means that theoretically it could
be usable on other platforms in the future.

Intermediate Language (IL)


Intermediate language (IL) is an object-oriented programming language designed to be
used by compilers for the .NET Framework before static or dynamic compilation to
machine code. The IL is used by the .NET Framework to generate machine-independent
code as the output of compilation of the source code written in any .NET programming
language.

IL is a stack-based assembly language that gets converted to byte code during execution
of a virtual machine. It is defined by the common language infrastructure (CLI)
specification. As IL is used for automatic generation of compiled code, there is no need
to learn its syntax. This term is also known as Microsoft intermediate language (MSIL)
or common intermediate language (CIL).

Just-In-Time (JIT) Compilation


A language-specific compiler converts the source code to the intermediate language.
This intermediate language is then converted into the machine code by the Just-In-Time
(JIT) compiler. This machine code is specific to the computer environment that the JIT
compiler runs on.
Advantages of .Net framework:
There are a number of advantages offered by the.Net framework, some of which are listed
below.
Memory Management:- In many programming languages, programmers are responsible for
sharing and releasing memory and managing the life of an object. For NET Framework
applications, CLR provides these services instead of an application.
Standard Type System:- In traditional planning languages, the basic types are defined by the
coordinator, making it difficult to integrate different languages. In .NET Framework, the basic
types are defined by the .NET Framework system and are common in all languages that direct
the .NET Framework.
Extensive Class Library:- Instead of writing large amounts of code to manage common low-
level tasks, editors can use the easily accessible library of genres and their members from the
.NET Framework Class Library.
Language interaction:- The language coordinators who direct the .NET Framework issue a
central code called the Common Intermediate Language (CIL), which is compiled during the
implementation of the common language. With this feature, single-language methods are
available in other languages, and editors can focus on creating applications in their preferred
language or languages.
SHASHI RAJ, BMSCW /Page 6
VB.Net Programming

Version Conformity:- With unusual exceptions, applications developed using a specific


version of the .NET Framework can work without modification in the latest version.

New Features in Visual Basic .NET

Visual Basic .NET, part of the Visual Studio .NET suite, boasts a number of new
features designed to make programming faster and easier. In addition to the basic
features, such as variables, data types, constants, arrays, enumerations, operators,
expressions, statements, and procedures.
Some of the new features of Visual Basic are:
1. Assemblies: An EXE or a DLL file that forms the basis of deployment, version
control, reuse, and security permissions of an application.
2. Namespaces: The components of assemblies, namespaces primarily organize the
objects present in the assemblies. An assembly can contain more than one
namespace.
3. Adding references: You need to add a reference to the external object that you
want to use in your current application.
4. Attributes: The tags that are used to provide additional information about the
elements defined in a Visual Basic .NET program. Some of the most common uses
of attributes are
 To explain COM properties for classes, interfaces, and methods
 To explain assemblies

SHASHI RAJ, BMSCW /Page 7


VB.Net Programming

 To specify security requirements of methods


 To specify features required to enforce security
5. Inheritance: Enables you to create classes that are derived from some other
classes known as base classes. Inheritance provides you the advantage of defining
a class only once. You can then reuse this functionality by deriving new classes
from this class.
6. Windows Forms: With a new forms package called Windows Forms, Visual
Basic .NET allows the developers to inherit a form from an existing form.
7. Structured exception handling: Enables you to create more efficient and robust
error handlers by using structured exception handling, which allows you to detect
and remove errors at runtime.
8. Multithreading: Enables your applications to handle multiple tasks
simultaneously.
9. VB.NET is a component-oriented language.
10.It can be learned easily.
11.It is a structured language.

Difference between VB.NET and Visual Basic

SHASHI RAJ, BMSCW /Page 8


VB.Net Programming

IDE and its components


The full name of IDE is an Integrated Development Environment. It is a software
application that allows developers to develop, run, test and debug software.
Generally, IDE consists of a code editor, a compiler, or an integrator and a debugger.

IDE has more features such as through this we can store the code online, format the
code and optimize the code and it has a lot of plug-in and extensions which is very
helpful in creating a rich application.

The IDE's toolbar looks like a word processor. This is called IDE because we can
access the necessary tools to develop the software application.
IDE components
The components of the IDE are as follows: -
Menu System: After you've started Visual Basic and have seen the Start page, you
often turn to the menu system to proceed, as when you want to create a new project and
use the File|New|Project menu item to bring up the New Project dialog box. The IDE
menu system is very involved, with many items to choose from-and you don't even see it
all at once. The menu system changes as you make selections in the rest of the IDE.
Menu bar: The menu bar is also common for all document windows. It contents
command required and build an application. The main menu items have some menu
items that can be chosen when needed.
Tool bar: The tool bars gives us quick access to commonly used menu command.
Beside the main tool bar, which is displays by default window the menu bar, visual basic
IDE provides additional tool bar for specific purpose. The four built in tool bar are
standard, edit, debug and from editor. By default, standard tool bar appear immediately
below the menu bar.
Form designer: For a software application, form objects are like building blocks. This is
the window from which the user interacts at the beginning of the application. Forms have
their own properties, events, and methods that we can control. The form window is a
window where we draw our application.
Tool box: The tool box contains the icon of the control we can place on a form to create
the application’s user interface. By default tool box contains a pointer icon and twenty
other icons of ActiveX controls. The tool boxes appear at the left side on screen by
default. User can change its position anywhere on the form. Even tool box can be turn
off on screen. To place a control on a form, we first select it with a mouse and then move
the mouse over the form. When the mouse is over the form, the curser turns into a large
plus sign, and we can draw control on the form, just as we would draw a circle using a
drawing application. The size of the circle determines the size of the control.

Property window: Every object has properties associated with it. The properties
window is docked under the project explorer window. The properties window allows us
to assign or change properties associated with a particular object. Properties are
SHASHI RAJ, BMSCW /Page 9
VB.Net Programming

attributes such as size, position etc. like a form, each control has its own set of
properties. Some properties like width, height are common to both form and controls,
while other properties are unique to form or control. Control offend differ in the number
and type of properties.

Code window: Normally code window not appear on screen because it is automatically
hidden. When we double click any control in the form, a code window will open. Visual
basic code window consist of two list boxes. Both list boxes appear at the top of the code
window. The left most list box is called object list box and right most list box is called
procedure list box.
Object list box allows us to select event procedure associated with a particular object.
The procedure list box allows us to select the event procedure associated with a
particular type of event such as click, drag drop, key down, mouse down etc.

Object Explorer: This tool lets you look at all the members of an object at once, The
Object Explorer helps open up any mysterious objects that Visual Basic has added to
your code so you can see what's going on inside. To open the Object Explorer, select
View|Other Windows|Object Explorer. The Object Explorer shows all the objects in your
program and gives you access to what's going on in all of them. To close the Object
Explorer, just click the X button at its upper

Solution Explorer: The Solution Explorer tracks the items in your projects; to add new
items, you can use the menu items in the Project menu, such as Add Windows Form and
Add User Control. To add new empty modules and classes to a project, you can use the
Project|Add New Items menu item. The Solution Explorer sees things in terms of files.
There, the References folder holds the currently referenced items (such as namespaces)
in a project, Assembly Info.vb is the file that holds information about the assembly
you're creating, and Form1.vb is the file that holds the code for the form under design.

Class View Window: If you click the Class View tab under the Solution Explorer,
you'll see the Class View window, this view presents solutions and projects in terms of
the classes they contain, and the members of these classes. Using the Class View
window gives you an easy way of jumping to a member of class that you want to access
quickly-just find it in the Class View window, and double-click it to bring it up in a code
designer.

Server Explorer: it's a great tool to help make distant servers feel less distant, because
you can see everything you need in an easy graphical environment. You can drag and
drop whole items onto Windows forms or Web forms from the Server Explorer.

Task List :It is another useful window. To see it, select the View|Show Tasks|All .As its
name implies, the Task List displays tasks that VB .NET assumes you still have to take
care of, and when you click a task, the corresponding location in a code designer
appears.

Output Window: Gives you the results of building and running programs.

SHASHI RAJ, BMSCW /Page 10


VB.Net Programming

Command Window: To open command window, click on View|Other


Windows|Command Window . you can enter commands like File.Add New Project here
and VB .NET will display the Add New Project dialog box.

UNIT 2 and UNIT 3


Creating applications with visual basic.net
Forms and Controls
Let's start with creating a Window Forms Application by following the following steps
in Microsoft Visual Studio: File  New Project  Windows Forms Applications
Finally, select OK, Microsoft Visual Studio creates your project and displays following
window Form with a name Form1.

Visual Basic Form is the container for all the controls that make up the user interface.
Every window you see in a running visual basic application is a form, thus the terms
form and window describe the same entity. Visual Studio creates a default form for you
when you create a Windows Forms Application.

Every form will have title bar on which the form's caption is displayed and there will be
buttons to close, maximize and minimize the form. 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.

SHASHI RAJ, BMSCW /Page 11


VB.Net Programming

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:

SHASHI RAJ, BMSCW /Page 12


VB.Net Programming

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:

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:

SHASHI RAJ, BMSCW /Page 13


VB.Net Programming

SHASHI RAJ, BMSCW /Page 14


VB.Net Programming

Controls
An object is a type of user interface element you create on a Visual Basic form by using
a toolbox control. In fact, in Visual Basic, the form itself is an object. Every Visual Basic
control consists of three important elements:

 Properties which describe the object,


 Methods cause an object to do something and
 Events are what happen when an object does something.
Control Properties
All the Visual Basic Objects can be moved, resized or customized by setting their
properties. A property is a value or characteristic held by a Visual Basic object, such as
Caption or Fore Color.

Properties can be set at design time by using the Properties window or at run time by
using statements in the program code.

Object.Property= Value
Where

 Object is the name of the object you're customizing.


 Property is the characteristic you want to change.
 Value is the new property setting.
For example,

Form1.Caption ="Hello"

You can set any of the form properties using Properties Window. Most of the properties
can be set or read during application execution. You can refer to Microsoft
documentation for a complete list of properties associated with different controls and
restrictions applied to them.

Control Methods
A method is a procedure created as a member of a class and they cause an object to do
something. Methods are used to access or manipulate the characteristics of an object or a
variable. There are mainly two categories of methods you will use in your classes:

 If you are using a control such as one of those provided by the Toolbox, you can call any
of its public methods. The requirements of such a method depend on the class being
used.

 If none of the existing methods can perform your desired task, you can add a method to a
class.

SHASHI RAJ, BMSCW /Page 15


VB.Net Programming

For example, the MessageBox control has a method named Show, which is called in the
code snippet below:

PublicClass Form1
PrivateSub Button1_Click(ByVal sender AsSystem.Object,ByVal e AsSystem.EventArgs)
Handles Button1.Click
MessageBox.Show ("Hello, World")
EndSub
EndClass

Control Events
An event is a signal that informs an application that something important has occurred.
For example, when a user clicks a control on a form, the form can raise a Click event
and call a procedure that handles the event. There are various types of events associated
with a Form like click, double click, close, load, resize, etc.
Following is the default structure of a form Load event handler subroutine. You can see
this code by double clicking the code which will give you a complete list of the all
events associated with Form control:

PrivateSub Form1_Load(sender AsObject, e AsEventArgs)HandlesMyBase.Load


'event handler code goes here
EndSub

Here, Handles MyBase.Load indicates that Form1_Load () subroutine


handles Load event. Similar way, you can check stub code for click, double click. If you
want to initialize some variables like properties, etc., then you will keep such code inside
Form1_Load() subroutine. Here, important point to note is the name of the event handler,
which is by default Form1_Load, but you can change this name based on your naming
convention you use in your application programming.

Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user interface.
Functionalities of all these controls are defined in the respective control classes. The
control classes are defined in the System.Windows.Forms namespace.
The following table lists some of the commonly used controls:

SHASHI RAJ, BMSCW /Page 16


VB.Net Programming

Data Types
Data types refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.

Data Types Available in VB.Net


VB.Net provides a wide range of data types. The following table shows all the data types
available:

SHASHI RAJ, BMSCW /Page 17


VB.Net Programming

Variables

What is a Variable?

 A variable is a simple name used to store the value of a specific data type in
computer memory.

SHASHI RAJ, BMSCW /Page 18


VB.Net Programming

 In VB.NET , each variable has a particular data type that determines the size,
range, and fixed space in computer memory.
 With the help of variable, we can perform several operations and manipulate
data values in any programming language.

VB.NET Variables Declaration

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

Syntax:

Dim [Variable_Name] As [Defined Data Type]

Name Descriptions
Dim It is used to declare and allocate the space for one or more
variables in memory.
Variable_Name It defines the name of the variable to store the values.
As It is a keyword that allows you to define the data type in the
declaration statement.
Data Type It defines a data type that allows variables to store data types such
as Char, String, Integer, Decimal, Long, etc.
Value Assign a value to the variable.

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

1. Dim Roll_no As Integer


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

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

Syntax:
Dim Variable_name1 As DataType1, variable_name2 As DataType2, Variable_name3
As DataType3

For example

Dim checker As Boolean


checker = False

SHASHI RAJ, BMSCW /Page 19


VB.Net Programming

MsgBox("The value of variable checker is : " & checker)

Dim x As Integer
x = 25
MsgBox("The value of variable x is : " & x)

Dim name As String


name = "II BCA STUDENTS “
MsgBox("The value of variable name is : " & name)

Constants

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

Declaration of Constants

 In VB.NET, const is a keyword that is used to declare a variable as constant.


 The Const statement can be used with module, structure, procedure, form,
and class.

Syntax: Const constname As datatype = value

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.
As It is a keyword that allows you to define the data type in the
declaration statement.
Data Type It defines a data type that allows variables to store data types such as
Char, 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

SHASHI RAJ, BMSCW /Page 20


VB.Net Programming

1. Const num As Integer = 10


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

Example of Const keyword

Const1.vb

Private Sub button1_Click() Dim


b As Integer, h As IntegerDim
area As Double
b = Val(Textbox1.Text) h
= Val(Textbox2.Text)
area = (0.5) * b * h
Label3.Caption = "Area of Triangle " & area
End Sub

Calculations
• Calculations can be performed with variables, constants, properties of certain
objects, and numeric literals.
• Do not use strings in calculations
• Values from Text property of Text Boxes
– Are strings, even if they contain numeric data
– Must be converted to a numeric data type before performing a calculation
Operators

Operator is a special symbol that tells the compiler to perform the specific logical or
mathematical operation on the data values. The data value itself (which can be either a
variable or a constant) is called an operand, and the Operator performs
various operations on the operand.

For example: In the expression,

3+2-1

The symbol + and - are the Operators, and the 3, 2, and 1 are operands.

Different Types of VB.NET Operators

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

o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators

SHASHI RAJ, BMSCW /Page 21


VB.Net Programming

o Bit Shift Operators


o Assignment Operators
o Concatenation Operators

Arithmetic Operators

The Arithmetic Operators in VB.NET, used to perform mathematical operations such


as subtraction, addition, multiplication, division, etc. on the operands in VB.NET.
These are as follows:

Arithmetic Operators in VB.NET

Operators Description Example


^ It is an exponentiation Operator that is used to raises one Y ^ X (X to
operand to the power of another operand. the power Y)
+ The addition Operator is used to add numeric data, as well X + Y
as concatenate two string variables.
- It is a subtraction Operator, which is used to subtract the X - Y
second operand from the first operand.
* The multiplication Operator is used to multiply the X * Y
operands
/ It is a division Operator used to divide one operand by X / Y
another operand and returns a floating-point result.
\ It is an integer division Operator, which is similar to X \ Y
division Operator, except that it returns an integer result
while dividing one operand to another operand.
Mod It is a modulo (Modulus) Operator, which is used to divide
two operands and returns only a remainder.

Comparison Operators

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

Operator Description Example


= It checks whether the value of the two operands is (A = B)
equal; If yes, it returns a true value, otherwise it
shows False.

SHASHI RAJ, BMSCW /Page 22


VB.Net Programming

<> It is a Non-Equality Operator that checks whether the (A <> B), check Non-
value of the two operands is not equal; it returns true; Equality
otherwise, it shows false.
> A greater than symbol or Operator is used to (A > B); if yes, TRUE,
determine whether the value of the left operand is
greater than the value of the right operand; If the Else FALSE
condition is true, it returns TRUE; otherwise, it
shows FALSE value.
< It is a less than symbol which checks whether the (A < B); if the
value of the left operand is less than the value of the condition is true,
right operand; If the condition is true, it returns returns TRUE else
TRUE; otherwise, it shows FALSE value. FALSE
>= It is greater than equal to which checks two A >= B
conditions whether the first operand is greater than or
equal to the second operand; if yes, it returns TRUE;
otherwise, it shows False.
<= This symbol represents less than equal to which A <= B
determines the first operand is less than or equal to
the second operand, and if the condition is true, it
returns TRUE; otherwise, it shows FALSE.
Is The Is Operator is used to validate whether the two result = obj1 Is obj2
objects reference the same variable or object; If the
test is true, it returns True; otherwise, the result is
False. In short, it checks the equality of the objects.
An Is Operator is also used to determine whether the
object refers to a valid object.
IsNot The IsNot Operator is similar to Is Operator, except Result = obj1 IsNot
that the two object references the different object; if obj2
yes, the result is True; otherwise, the result is False.
Like The Like Operator is used to check the pattern result = string Like the
expression of string variable; And if the pattern pattern, the pattern
matched, the result is True; otherwise, it returns represents the series of
False. characters used by Like
Operator.

Logical and Bitwise Operators

The logical and bitwise Operators work with Boolean (true or false) conditions, and if
the conditions become true, it returns a Boolean value. The following are the logical and
bitwise Operators used to perform the various logical operations such as And, Or, Not,

SHASHI RAJ, BMSCW /Page 23


VB.Net Programming

etc. on the operands (variables). Suppose there are two operand A and B, where A is
True, and B is False.

Operator Description Example


And The And Operator represents, whether both the operands are (A And B),
true; the result is True. result = False
Or It is an Or Operator that returns a true value; if anyone (A Or B),
operand is true from both the operands. result = True
Not The Not Operator is used to reverse the logical condition. For Not A
example, if the operand's logic is True, it reveres the
condition and makes it False. Or

Not(A And B)
is True
Xor It is an Exclusive OR Operator that represents, whether both A Xor B is
the expression is true or false, the result is True; otherwise, True
the result is False.
AndAlso It is a logical AND Operator that performs short-circuit A AndAlso B
operation on the variables, and if both the operands are true, = False
the result is True else the result is False.
OrElse It is a logical OR Operator that perform short-circuit A OrElse B =
operation on Boolean data. If anyone of the operand is true, True
the result is True else the result is False.
IsFalse The IsFalse Operator is used to determine whether an
expression is False.
IsTrue The IsTrue Operator is used to determine whether an
expression is True.

Bit Shift Operators

The Bit Shit Operators are used to perform the bit shift operations on binary values either
to the right or to the left.

Bit Shift operations in VB.NET

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

SHASHI RAJ, BMSCW /Page 24


VB.Net Programming

the bit found in either operand.


XOR The Binary XOR Operator in VB.NET, used to determine whether a bit is
available to copy in one operand instead of both.
Not The binary NOT Operator is also known as the binary Ones' Compliment
Operator, which is used to flip binary bits. This means it converts the bits from
0 to 1 or 1 to 0 binary bits.
<< The Binary Left Shift Operator is used to shift the bit to the left side.
>> The Binary Right Shift Operator is used to shift the bit to the right side.

Assignment Operators

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

Assignment Operators in VB.NET

Operator Description Example


= It is a simple assignment Operator used to assign a X = 5, X assign a value
right-side operand or value to a left side operand. 5
X = P + Q, (P + Q)
variables or value assign
to X.
+= An Add AND assignment Operator is used to add X += 5, which means
the value of the right operand to the left operand. X= X+5 ( 5 will add and
And the result is assigned to the left operand. assign to X and then
result saved to Left X
operand)
-= It is a Subtract AND assignment Operator, which X -= P, which is same as
subtracts the right operand or value from the left X = X - P
operand. And then, the result will be assigned to the
left operand.
*= It is a Multiply AND assignment Operator, which X *= P, which is same
multiplies the right operand or value with the left as X = X - P
operand. And then, the result will be assigned to the
left operand.
/= It is a Divide AND assignment Operator, which X /= P, which is same as
divides the left operand or value with the right X = X - P
operand. And then, the result will be assigned to the
left operand (in floating-point).
\= It is a Divide AND assignment Operator, which X \= P, which is same as

SHASHI RAJ, BMSCW /Page 25


VB.Net Programming

divides the left operand or value with the right X = X - P


operand. And then, the result will be assigned to the
left operand (in integer-point division).
^= It is an expression AND assignment Operator, X ^= P, which is same as
which raises the left operand or value to the right X = X ^ P
operand's power. And then, the result will be
assigned to the left operand.
&= It is a concatenate string assignment Operator used Str &= name, which is
to bind the right-hand string or variable with the same as Str = Str &
left-hand string or variable. And then, the result will name
be assigned to the left operand.

Concatenation Operators

In VB.NET, there are two concatenation Operators to bind the operands:

Operator Description Example


& It is an ampersand symbol that is used to bind two or more Result = Wel
operand together. Furthermore, a nonstring operand can also be & come,
concatenated with a string variable ( but in that case, Option Result =
Strict is on). Welcome
+ It is also used to add or concatenate two number or string. Result = Wel
+ come,
Result =
Welcome

Making Decisions (Control Structures)


In a program, statements may be executed sequentially, selectively or iteratively. Every
programming language provides constructs to support sequence, selection or iteration. So
there are three types of programming constructs:
 Sequential Constructs
 Selection Constructs
 Iterative Constructs(Loops)

 Sequential Construct
The sequential construct means the statements are being executed sequentially. This
represents the default flow of statements.

SHASHI RAJ, BMSCW /Page 26


VB.Net Programming

 Selection Construct
The selection construct means the execution of statement(s) depending upon the
condition-test. If a condition evaluates to true, a course-of-action (a set of statements) is
followed otherwise another course-of-action is followed. This construct is also called
decision construct as it helps in decision making.

 Iterative Constructs
The iterative or repetitive constructs means repetition of a set-of-statements depending
upon a condition-test. A set-of-statements are repeated again and again till the condition
or Boolean Expression evaluates to true. The iteration constructs are also called as
looping constructs.

SHASHI RAJ, BMSCW /Page 27


VB.Net Programming

Selection Constructs

VB provides two types of selection construct:

1) If statement
2) Select Case statement
The If Statement: If statements of VB come in various forms & are given below:
1) If..Then Statement
2) If..Then..Else Statement
3) If..Then..ElseIf Statement
4) Nested Ifs

1. If..Then Statement
An If..Then statement tests a particular condition; if the condition evaluates to true, a
course-of-action is followed otherwise it is ignored.
Syntax:
If (Boolean expression) Then
Statements
End If

2. If..Then..Else Statement
If..Then..Else statement provides an alternate choice to the user i.e. if the condition is
true then a set of statements are executed otherwise another set of statements are
executed.

Syntax:

If (Boolean Expression) Then


VB Statement(s)

SHASHI RAJ, BMSCW /Page 28


VB.Net Programming

Else
VB Statement(s)
End If

3. If..Then..ElseIf Statement

If..Then..ElseIf statement is used to test a number of mutually exclusive cases and only
executes one set of statements for the case that is true first.
Syntax:

If (Boolean Expression) Then


Statement(s)
ElseIf (Boolean Expression 2) Then
Statement(s)
ElseIf (Boolean Expression 3) Then
Statement(s)
:
[Else
Statement(s)
End If

4. Nested Ifs
A nested If is an if that has another If in its if’s body or in its else’s body.
Syntax:

If (expresssion 1) Then
If (expression 2 ) Then
Statement 1
[Else
Statement 2
End If
Else
body-of-else]
End If

Select-Case Statement

Select-Case is a multiple branching statement and is used to execute a set of statements


depending upon the value of the expression. It is better to use Select-Case statement in
comparison to If..Then..ElseIf Statement when the numbers of checks are more. There
are 3 different forms of using Select-Case statements and are given below:

SHASHI RAJ, BMSCW /Page 29


VB.Net Programming

Syntax:

Select Case Expression


Case is relation :
’one or more visual basic statements
Case is relation :
’one or more visual basic statements
Case Else :
’one or more visual basic statements
End Select
Iterative Constructs (Looping Structures)
VB offers broadly following three types of looping structures:
1. For..Next
2. For Each...Next
3. Do Loop
a. Do While..Loop
b. Do..Loop While
c. Do Until..Loop
d. Do..Loop Until
4. While..Wend
1. For..Next
The For…Next Statements are used repeat a set of statements for specific number of
Times.
Syntax:

For counter = <start value> to <end value>[Step Value]


Executable Statements
Exit For
Next [counter]

Counter is any numeric value.

Start value is the initial value of the counter.


2. For Each...Next

SHASHI RAJ, BMSCW /Page 30


VB.Net Programming

It repeats a group of statements for each element in a collection. This loop is used for
accessing and manipulating all elements in an array or a VB.Net collection.
Syntax:
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]

3. Do..Loop Structures
a. Do While..Loop :
Do While loop is an entry controlled loop in which the condition is placed at the
entry point. This statement executes the statements specified in the body of the loop till
the condition evaluates to true. The loop may not be executed at all the if the condition is
initially false.
Syntax:
Do While<condition or boolean expression>
‘ One or more VB Statements
Loop
b. Do..Loop While
Do Loop While is an exit controlled loop as the condition is placed at exit
point. The body of the loop is going to be executed at least once whether the condition
evaluates to true or false. Loop is executed as long as the result of the condition remains
true.
Syntax:
Do
One or more VB Statements
Loop While <condition or Boolean Expression>
c. Do..Until Loop
Do Until loop is an entry controlled loop in which the condition is placed at
the entry point. This statement executes the statements specified in the body of the loop
till the condition evaluates to false. The loop may not be executed at all the if the
condition is initially true.
Syntax:
Do Until <condition or boolean expression>
SHASHI RAJ, BMSCW /Page 31
VB.Net Programming

‘ One or more VB Statements


Loop
d. Do..Loop Until
Do Loop Until is an exit controlled loop as the condition is placed at exit point.
The body of the loop is going to be executed at least once whether the condition
evaluates to true or false. Loop is executed as long as the result of the condition remains
false.
Syntax:
Do
One or more VB Statements
Loop Until <condition or Boolean Expression>
4. While..Wend
While..Wend loop is functionally equivalent to the Do While..Loop. It executes a set of
VB statements till the condition evaluates to true.
Syntax:
While <Condition>
one or more vb statements
Wend

Working with Strings

In VB.NET, string is a sequential collection of characters that is called a text. The String
keyword is used to create a string variable that stores the text value. The name of the
string class is System.String that contains the various function of string.

Declaration and Initialization of String

The following are the different ways to declare and initialize the string variable using the
String keyword in the VB.NET programming language

Declaration of the String variable


Dim str As String
Dim abc As String

' Initialization of String variable


Dim str As String = "Welcome to VB.NET Programming."
Dim str1 As String = "Hello World!"

' Initialize a null string


SHASHI RAJ, BMSCW /Page 32
VB.Net Programming

Dim str2 As String = Nothing

' Initialization of an empty string


Dim name As String = String.Empty

' Creating a String from char


Dim letter As Char() = {"H", "E", "L", "L", "O" }

In the above declaration of string, we have defined the string variable with
string keyword and initialize string variable with value based on our requirements.

Lists
The List class is used to store generic types of collections objects. By using a generic
class on the list, we can store one type of object. The List size can be dynamically
different depending on the need of the application, such as adding, searching or inserting
elements into a list.

A VB.NET List class is provided by the System.Collection.Generic namespace.

Properties of the VB.NET List

The following are the commonly used properties of the List.

Property Description
name

Capacity It is used to obtain or set a number that indicates the number of elements
can be placed in a list.

Count It is used to count the number of elements available in the List.

Item It is used to get or set an item at a specified position of the List.

VB.NET List Methods

The following are the methods of VB.NET List class for performing various operations
like add, search, remove, sort.

SHASHI RAJ, BMSCW /Page 33


VB.Net Programming

Method Description

Add As the name represents, the Add() method is used to add an object at the
end of the List

AddRange It is used to add the elements of the specified collection to the end of the
List.

Clear It is used to clear all records from the List.

Contains It is used to validate whether the specified object exists in the List or not.

CopyTo A CopyTo() method is used to copy all records of a list into a one-
dimensional array.

Find A Find() method is used to search for a specified element from a list that
matches the defined state and returns the first occurrence.

FindAll A FindAll() method is used to fetch all the elements from a list that
matches the condition defined by the specified predicate.

Insert It is used to insert an element at the specified position of the List.

InsertRange It is used to insert all elements of a specified collection in a list start from a
specified location.

Remove By using the Remove() method, we can delete a specified element from the
list.

RemoveAt By using the RemoveAt() method in a list, we can delete an element from
the specified location in a list.

Reverse The Reverse() method is used to reverse the order list of elements.

Sort A Sort() method is used to sort the elements of the list.

ToArray It is used to copy all the elements of the list to a new array object.

SHASHI RAJ, BMSCW /Page 34


VB.Net Programming

Validation control
Validation controls are used to validate the data of an input control. If the data does not
pass validation, it will display an error message to the user. It is very-very useful in
client side validation.

Validation in database

Validation is the name given to the process whereby the information entered in the
database is checked to ensure that it makes sense. For example, you can use validation to
check that only numbers between 0 and 100 are entered in a percentage field, or only
Male or Female is entered in a sex field.

Uses of validation

The most basic use of validation functions is to ensure that documents are properly
formed to fit your application’s expectations. Without validation, you need to check for
the existence of all fields on a document that your Map Reduce or user-interface code
needs to function.

Client side validation


When you enter data, the browser and/or the web server will check to see that the data is
in the correct format and within the constraints set by the application. Validation done in
the browser is called client-side validation, while validation done on the server is called
server-side validation.

ASP.NET validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don’t get stored.
ASP.NET provides the following validation controls:
 Required Field Validator,
 RangeValidator,
 CompareValidator.

Procedures
A procedure is a group of statements that together perform a task when called. After the
procedure is executed, the control returns to the statement calling the procedure. VB.Net
has two types of procedures:
 Functions 
 Sub procedures or Subs 
Functions return a value, whereas Subs do not return a value.

SHASHI RAJ, BMSCW /Page 35


VB.Net Programming

Functions
Defining a Function
The Function statement is used to declare the name, parameter and the body of a
function. The syntax for the Function statement is:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function

Where,
 Modifiers: specify the access level of the function; possible values are: Public,
Private, Protected, Friend, Protected Friend and information regarding
overloading, overriding, sharing, and shadowing. 
 FunctionName: indicates the name of the function
 ParameterList: specifies the list of the parameters
 ReturnType: specifies the data type of the variable the function returns 


Function Returning a Value


In VB.Net, a function can return a value to the calling code in two ways:
 By using the return statement
 By assigning the value to the function name

Recursive Function: Afunction can call itself. This is known as recursion.

Param Arrays: At times, while declaring a function or sub procedure, you are not sure of
the number of arguments passed as a parameter.

Different types of functions

A function is similar to a normal procedure but the main purpose of the function is to
accept a certain input from the user and return a value which is passed on to the main
program to finish the execution. There are two types of functions, the built-in functions
(or internal functions) and the functions created by the programmers.

SHASHI RAJ, BMSCW /Page 36


VB.Net Programming

Sub Procedures
The Sub statement is used to declare the name, parameter and the body of a sub
procedure. The syntax for the Sub statement is:

[Modifiers] Sub SubName [(ParameterList)]


[Statements]
End Sub

Where,

 Modifiers: specify the access level of the procedure; possible values are: Public,
Private, Protected, Friend, Protected Friend and information regarding
overloading, overriding, sharing, and shadowing. 

 SubName: indicates the name of the Sub

 ParameterList: specifies the list of the parameters

Passing Parameters by Value


This is the default mechanism for passing parameters to a method. In this mechanism,
when a method is called, a new storage location is created for each value parameter. The

SHASHI RAJ, BMSCW /Page 37


VB.Net Programming

values of the actual parameters are copied into them. So, the changes made to the
parameter inside the method have no effect on the argument.

In VB.Net, you declare the reference parameters using the ByVal keyword.

Passing Parameters by Reference


A reference parameter is a reference to a memory location of a variable. When you pass
parameters by reference, unlike value parameters, a new storage location is not created
for these parameters. The reference parameters represent the same memory location as
the actual parameters that are supplied to the method.

In VB.Net, you declare the reference parameters using the ByRef keyword.

The Type Conversion Functions in VB.Net


VB.Net provides the following in-line type conversion functions:

SHASHI RAJ, BMSCW /Page 38


VB.Net Programming

Multiple Forms
VB.Net allows working with multiple forms. Every form in Visual Basic.Net is known
as windows. A Windows application can either be a Single Form application or multiple
form application.

Add New Form to the Project

 Many times we want to add new forms to our project. We can add a new form to
the project by selecting Project->Add New Item from the main menu which
displays a window which has many items to add to your project.
 Select Windows Form from that window and click on Add button to add a new
form to the project.
 We can also add a new form from the Solution Explorer. To add a new form from
the Solution Explorer, right-click on the project name in Solution Explorer and
Select Add->Windows Form which again displays a window select Windows
Form and click on Add button.
 Now you have to make some changes if you want to display the form which you
added when you run the application. For this right-click on the project name
in Solution Explorer select Properties which displays a Window.
 On this window click the drop-down box named as Startup Form. By this you can
able to see each and every form of your project.
 Now which form you want to displayed when you run the application select that
form and run your application. When you run the application, the form you
assigned as Startup Form will be displayed.

Working with Multiple Forms

In visual Basic .NET we can work with multiple forms. For example, take three forms in
your application Form1, Form2 and Form3. Now drag a buttons form the toolbox
on Form1 andForm2. Now we want to open Form2 when a button on the Form1 is
clicked and when we clicked the button on Form2, Form3 will displayed. Double click
on Button1 on Form1 and place the code given below in the click event of the button.
Public Class Form1

Dim F2 As New Form2


'creating a reference to Form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles Button1.Click
F2.Show()
End Sub
End Class

SHASHI RAJ, BMSCW /Page 39


VB.Net Programming

After that, Double click on Button1 on Form2 and place the code given below in the
click event of the button.
Public Class Form2

Dim F3 As New Form3


'creating a reference to Form3
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles Button1.Click
F3.Show()
End Sub
End Class

Standard Modules

Standard modules (.BAS file name extension) are containers for procedures and
declarations commonly accessed by other modules within the application. They can
contain global (available to the whole application) or module-level declarations of
variables, constants, types, external procedures, and global procedures.

Menu Control

A menu is used as a menu bar in the Windows form that contains a list of related
commands, and it is implemented through MenuStrip Control. The Menu control is also
known as the VB.NET MenuStrip Control.

The menu items are created with ToolStripMenuItem Objects. Furthermore,


the ToolStripDropDownMenu and ToolStripMenuItem objects enable full control
over the structure, appearance, functionalities to create menu items, submenus, and drop-
down menus in a VB.NET application.

Properties of the MenuStrip Control

Properties Description
CanOverflow The CanOverflow property is used to authenticate whether the
control supports overflow functionality by setting values in the
MenuStrip control.
Stretch The Stretch property is used to obtain a value that specifies whether
the menustrip stretches from end to end in the MenuStrip control.
GripStyle The GripStyle property obtains or sets the visibility of the grip that
uses the reposition of the menu strip control.
ShowItemToolTips It is used to obtain or set the value that determines if the ToolTips
are displayed for the MenuStrip Control.
DefaultSize The DefaultSize property is used to get the default horizontal and
vertical dimension of the MenuStrip in pixel when it is first created.

SHASHI RAJ, BMSCW /Page 40


VB.Net Programming

Methods of the MenuStrip Control

Method Description
CreateAccessibilityInstance() It is used to create a new accessibility instance for the
MenuStrip Control.
ProcessCmdKey() The ProcessCmdKey method is used to process the
command key in the MenuStrip Control.
CreateDefaultItem() The CreateDefaultItem method is used to create a
ToolStripMenuItem with the specified text, image, and
event handlers for the new MenuStrip.
OnMenuActivate() It is used to initiate the MenuActivate event in the
MenuStrip control.
OnMenuDeactivate() It is used to start the MenuDeactivate event in the
MenuStrip control.

Events of the MenuStrip Control

Events Description
MenuActivate When a user uses a menu bar control with a mouse or keyboard, a
MenuActivate event occurs.
MenuDeactivate The MenuDeactivate event occurs when the MenuStrip control is
deactivated in the Windows form.

ARRAYS
 Array declarations in Visual Basic .NET are similar in Visual Basic.net and
other languages. For example, here is a declaration of an Integer array that
has five elements:
Dim a(4) As Integer
 The literal 4 in this declaration specifies the upper bound of the array.
 All arrays in Visual Basic .NET have a lower bound of 0, so this is a
declaration of an array with five elements, having indexes 0, 1, 2, 3, and 4.
 The previous declaration is of a variable named a, which is of type "array
of Integer." Array types implicitly inherit from the .NET Framework's

SHASHI RAJ, BMSCW /Page 41


VB.Net Programming

Array type (defined in the System namespace) and, therefore, have access to
the methods defined in that type.
Multidimensional Arrays

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

Fixed-Size Arrays
A fixed-size array holds a fixed number of elements. This means that you must define
the number of elements that it will hold during its definition. Suppose you need an array
to hold only 3 student names.
You can define and initialize the array as follows:
Dim students(0 to 2) As String
students(0) = "John"
students (1) = "Alice"
students (2) = "Antony"
We began by declaring a string array named students. The 0 to 2 declares that the array
will store elements from its index 0 to index 2, meaning we will have 3 elements in total.

SHASHI RAJ, BMSCW /Page 42


VB.Net Programming

To add elements to the array, we have used the array name and specified the index at
which the element will be stored. For example, the name John will be stored at index 0
of the array, meaning that it will form the first element of the array. Antony will be the
last element of the array.

Static array:
 Array is dimensioned during design time.

 Array size cannot be changed.


 By using erase function, only array element values in the memory will be emptied,
elements memory will not be deleted.
 Memory is fixed during design time.
Dynamic Arrays.
• Many times we feel that the size of array in not enough or too much then required. The
array will allocate memory location when its declared, so to release or add more we
need to change the dimension of the array which has been pre-declared.
• We can create a dynamic array by not specifying the size of the array at the time of
array declaration.
Syntax:Dim student_names() as string
In the above syntax you will see that numbers of elements are not mentioned. Now to
redeclarethe elements we make use of ReDim for an array to change its dimension.
e.g.Dimstudent_names() as string
ReDimstudent_names(10)
• ReDim can also change the size of multi-dimensional arrays.
• You can change the number of dimensions in an array, but you cannot make a
multidimensional array to a single dimension or lesser than the original dimension.
Timer Control

The timer control is a looping control used to repeat any task in a given time interval. It
is an important control used in Client-side and Server-side programming, also in
Windows Services.

Furthermore, if we want to execute an application after a specific amount of time, we can


use the Timer Control. Once the timer is enabled, it generates a tick event handler to
perform any defined task in its time interval property. It starts when the start() method of
timer control is called, and it repeats the defined task continuously until the timer stops.

SHASHI RAJ, BMSCW /Page 43


VB.Net Programming

Timer Control Properties

Properties Description
Name The Name property is used to set the name of the control.
Enabled The Enables property is used to enable or disable the timer control. By
default, it is True.
Interval An Interval property is used to set or obtain the iteration interval in
milliseconds to raise the timer control's elapsed event. According to the
interval, a timer repeats the task.
AutoReset The AutoReset property is used to obtain or set a Boolean value that
determines whether the timer raises the elapsed event only once.
Events Events property are used to get the list of event handler that is
associated with Event Component.
CanRaiseEvents It is used to get a value that represents whether the component can raise
an event.

Events of Timer Control

Events Description
Disposed When control or component is terminated by calling the Dispose method, a
Dispose event occurs.
Elapsed When the interval elapses in timer control, the Elapsed event has occurred.
Tick A tick event is used to repeat the task according to the time set in the Interval
property. It is the default event of a timer control that repeats the task between
the Start() and Stop() methods.

Methods of Timer Control

Methods Description
BeginInt() The BeginInt() method is used to start run time initialization of a timer
control used on a form or by another component.
Dispose() The Dispose() method is used to free all resources used by the Timer
Control or component.
Dispose(Boolean) It is used to release all resources used by the current Timer control.
Close() The Close() method is used to release the resource used by the Timer
Control.

SHASHI RAJ, BMSCW /Page 44


VB.Net Programming

Start() The Start() method is used to begin the Timer control's elapsed event
by setting the Enabled property to true.
EndInt() The EndInt() method is used to end the run time initialization of timer
control that is used on a form or by another component.
Stop() The Stop() method is used to stop the timer control's elapsed event by
setting Enabled property to false.

File Handling
A file is a collection of data stored in a disk with a specific name and a directory path.
When a file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication path.
There are two main streams: the input stream and the output stream. The input stream is
used for reading data from file (read operation) and the output stream is used for writing
into the file (write operation).
VB.Net I/O Classes
The System.IO namespace has various classes that are used for performing various
operations with files, like creating and deleting files, reading from or writing to a file,
closing a file, etc.
The following table shows some commonly used non-abstract classes in the System.IO
namespace −

I/O Class Description


BinaryReader Reads primitive data from a binary stream.
BinaryWriter Writes primitive data in binary format.
BufferedStream A temporary storage for a stream of bytes.
Directory Helps in manipulating a directory structure.
DirectoryInfo Used for performing operations on directories.
DriveInfo Provides information for the drives.
File Helps in manipulating files.
FileInfo Used for performing operations on files.
FileStream Used to read from and write to any location in a file.
MemoryStream Used for random access of streamed data stored in memory.
Path Performs operations on path information.
StreamReader Used for reading characters from a byte stream.

SHASHI RAJ, BMSCW /Page 45


VB.Net Programming

StreamWriter Is used for writing characters to a stream.


StringReader Is used for reading from a string buffer.
StringWriter Is used for writing into a string buffer.

The FileStream Class


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

FileMode The FileMode enumerator defines various methods for opening files. The
members of the FileMode enumerator are −
 Append − It opens an existing file and puts cursor at the end of file, or
creates the file, if the file does not exist.
 Create − It creates a new file.
 CreateNew − It specifies to the operating system that it should create
a new file.
 Open − It opens an existing file.
 OpenOrCreate − It specifies to the operating system that it should
open a file if it exists, otherwise it should create a new file.
 Truncate − It opens an existing file and truncates its size to zero
bytes.
FileAccess FileAccess enumerators have members: Read, ReadWrite and Write.

FileShare FileShare enumerators have the following members −


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

SHASHI RAJ, BMSCW /Page 46


VB.Net Programming

EXCEPTION HANDLING
An exception is a problem that arises during the execution of a program. An exception
is a response to an exceptional circumstance that arises while a program is running, such
as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another.
VB.Net exception handling is built upon four keywords:
Try, Catch,Finally and Throw.
 Try: A Try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more Catch blocks.

 Catch: A program catches an exception with an exception handler at the place in


a program where you want to handle the problem. The Catch keyword indicates
the catching of an exception.

 Finally: The Finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be
closed whether an exception is raised or not.

 Throw: A program throws an exception when a problem shows up. This is done
using a Throw keyword.

Syntax
Assuming a block will raise an exception, a method catches an exception using a
combination of the Try and Catch keywords. A Try/Catch block is placed around the
code that might generate an exception. Code within a Try/Catch block is referred to as
protected code, and the syntax for using Try/Catch looks like the following:

Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try

SHASHI RAJ, BMSCW /Page 47


VB.Net Programming

Exception Classes in .Net Framework


In the .Net Framework, exceptions are represented by classes. The exception classes in
.Net Framework are mainly directly or indirectly derived from
theSystem.Exception class.

Some of the exception classes derived from the System.Exception class are
the System.ApplicationException andSystem.SystemException classes.

The System.ApplicationException class supports exceptions generated by application


programs. So the exceptions defined by the programmers should derive from this class.

The System.SystemException class is the base class for all predefined system
exception.The following table provides some of the predefined exception classes
derived from the Sytem.SystemException class:

Exception Class Description

System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeException Handles errors generated when a method refers


to an array index out of range.

System.ArrayTypeMismatchException Handles errors generated when type is


mismatched with the array type.

System.NullReferenceException Handles errors generated from deferencing a


null object.

System.DivideByZeroException Handles errors generated from dividing a


dividend with zero.

System.InvalidCastException Handles errors generated during typecasting.

System.OutOfMemoryException Handles errors generated from insufficient free


memory.

System.StackOverflowException Handles errors generated from stack overflow.

SHASHI RAJ, BMSCW /Page 48


VB.Net Programming

Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the form of
try and catch blocks. Using these blocks the core program statements are separated from
the error-handling statements.These error handling blocks are implemented using
the Try, Catch and Finallykeywords

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes are derived
from the ApplicationException class.

Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.

Events
Events are basically a user action like key press, clicks, mouse movements, etc., or
some occurrence like system generated notifications. Applications need to respond to
events when they occur.

Clicking on a button, or entering some text in a text box, or clicking on a menu item, all
are examples of events. An event is an action that calls a function or may cause another
event.

Event handlers are functions that tell how to respond to an event.

VB.Net is an event-driven language. There are mainly two types of events:

 Mouse events

 Keyboard events

Handling Mouse Events


Mouse events occur with mouse movements in forms and controls. Following are the
various mouse events related with a Control class:

 MouseDown - it occurs when a mouse button is pressed

 MouseEnter - it occurs when the mouse pointer enters the control

 MouseHover - it occurs when the mouse pointer hovers over the control

 MouseLeave - it occurs when the mouse pointer leaves the control

 MouseMove - it occurs when the mouse pointer moves over the control

SHASHI RAJ, BMSCW /Page 49


VB.Net Programming

 MouseUp - it occurs when the mouse pointer is over the control and the mouse
button is released

 MouseWheel - it occurs when the mouse wheel moves and the control has focus

The event handlers of the mouse events get an argument of type MouseEventArgs. The
MouseEventArgs object is used for handling mouse events. It has the following
properties:

 Buttons - indicates the mouse button pressed

 Clicks - indicates the number of clicks

 Delta - indicates the number of detents the mouse wheel rotated

 X - indicates the x-coordinate of mouse click

 Y - indicates the y-coordinate of mouse click

Handling Keyboard Events


Following are the various keyboard events related with a Control class:

 KeyDown - occurs when a key is pressed down and the control has focus

 KeyPress - occurs when a key is pressed and the control has focus

 KeyUp - occurs when a key is released while the control has focus

The event handlers of the KeyDown and KeyUp events get an argument of
typeKeyEventArgs. This object has the following properties:

 Alt - it indicates whether the ALT key is pressed/p>

 Control - it indicates whether the CTRL key is pressed

 Handled - it indicates whether the event is handled

 KeyCode - stores the keyboard code for the event

 KeyData - stores the keyboard data for the event

 KeyValue - stores the keyboard value for the event

 Modifiers - it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed

 Shift - it indicates if the Shift key is pressed

SHASHI RAJ, BMSCW /Page 50


VB.Net Programming

The event handlers of the KeyDown and KeyUp events get an argument of type
KeyEventArgs. This object has the following properties:

 Handled - indicates if the KeyPress event is handled

 KeyChar - stores the character corresponding to the key pressed

Working with Databases


Applications communicate with a database, firstly, to retrieve the data stored there and
present it in a user-friendly way, and secondly, to update the database by inserting,
modifying and deleting data.
Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework
that is used by the .Net applications for retrieving, accessing and updating data.
Advanced Databases Programming using ADO.Net

ADO.Net Object Model


ADO.Net object model is nothing but the structured process flow through various
components. The object model can be pictorially described as −

The data residing in a data store or database is retrieved through the data provider.
Various components of the data provider retrieve data for the application and update
data.
An application accesses data either through a dataset or a data reader.
 Datasets store data in a disconnected cache and the application retrieves data from it.
 Data readers provide data to the application in a read-only and forward-only mode.

SHASHI RAJ, BMSCW /Page 51


VB.Net Programming

Data Provider class


A data provider is used for connecting to a database, executing commands and retrieving
data, storing it in a dataset, reading the retrieved data and updating the database.
The data provider in ADO.Net consists of the following four objects −

Sr.No. Objects & Description

1 Connection
This component is used to set up a connection with a data source.

2 Command
A command is a SQL statement or a stored procedure used to retrieve, insert, delete
or modify data in a data source.

3 DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-
only mode.

4 DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a
database through a data adapter. It retrieves data from a database into a dataset and
updates the database. When changes are made to the dataset, the changes in the
database are actually done by the data adapter.

There are following different types of data providers included in ADO.Net


 The .Net Framework data provider for SQL Server - provides access to Microsoft
SQL Server.
 The .Net Framework data provider for OLE DB - provides access to data sources
exposed by using OLE DB.
 The .Net Framework data provider for ODBC - provides access to data sources
exposed by ODBC.
 The .Net Framework data provider for Oracle - provides access to Oracle data
source.
DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached set of
records that are retrieved from a database. When a connection is established with the
database, the data adapter creates a dataset and stores data in it. After the data is retrieved
and stored in a dataset, the connection with the database is closed. This is called the

SHASHI RAJ, BMSCW /Page 52


VB.Net Programming

'disconnected architecture'. The dataset works as a virtual database containing tables,


rows, and columns.
The following diagram shows the dataset object model −

The DataSet class is present in the System.Data namespace. The following table
describes all the components of DataSet −

Sr.No. Components & Description

1 DataTableCollection
It contains all the tables retrieved from the data source.

2 DataRelationCollection
It contains relationships and the links between tables in a data set.

3 Extended Properties
It contains additional information, like the SQL statement for retrieving data, time of
retrieval, etc.

4 DataTable
It represents a table in the DataTableCollection of a dataset. It consists of the
DataRow and DataColumn objects. The DataTable objects are case-sensitive.

5 DataRelation

SHASHI RAJ, BMSCW /Page 53


VB.Net Programming

It represents a relationship in the DataRelationshipCollection of the dataset. It is used


to relate two DataTable objects to each other through the DataColumn objects.

6 DataRowCollection
It contains all the rows in a DataTable.

7 DataView
It represents a fixed customized view of a DataTable for sorting, filtering, searching,
editing and navigation.

8 PrimaryKey
It represents the column that uniquely identifies a row in a DataTable.

9 DataRow
It represents a row in the DataTable. The DataRow object and its properties and
methods are used to retrieve, evaluate, insert, delete, and update values in the
DataTable. The NewRow method is used to create a new row and the Add method
adds a row to the table.

10 DataColumnCollection
It represents all the columns in a DataTable.

11 DataColumn
It consists of the number of columns that comprise a DataTable.

The Connection object provides connectivity to a data source.

The Command object enables access to database commands to return data, modify data,
run stored procedures, and send or retrieve parameter information.

The DataAdapter Object


The DataAdapter object acts as a mediator between the DataSet object and the database.
This helps the Dataset to contain data from multiple databases or other data source.
an adapter supports the following four properties:
 Select Command – reference to a command (SQL statement or stored procedure
name) that retrieves rows from the data store.
 Insert Command – reference to a command for inserting rows into the data store.
 Update Command – reference to a command for modifying rows in the data store.
SHASHI RAJ, BMSCW /Page 54
VB.Net Programming

 Delete Command – reference to a command for deleting rows from the data store.
The DataReader Object
The DataReader object is an alternative to the DataSet and DataAdapter combination.
This object provides a connection oriented access to the data records in the database.
These objects are suitable for read-only access, such as populating a list and then
breaking the connection.
Important Classes in ADO.NET
1. Connection Class
2. Command Class
3. DataReader Class
4. DataAdaptor Class
5. DataSet.Class

1. Connection Class
In ADO.NET, we use these connection classes to connect to the database. These
connection classes also manage transactions and connection pooling.

2. Command Class
The Command class provides methods for storing and executing SQL statements and
Stored Procedures. The following are the various commands that are executed by the
Command Class.
 ExecuteReader: Returns data to the client as rows. This would typically be an SQL
select statement or a Stored Procedure that contains one or more select statements.
This method returns a DataReader object that can be used to fill a DataTable object or
used directly for printing reports and so forth.
 ExecuteNonQuery: Executes a command that changes the data in the database, such
as an update, delete, or insert statement, or a Stored Procedure that contains one or
more of these statements. This method returns an integer that is the number of rows
affected by the query.
 ExecuteScalar: This method only returns a single value. This kind of query returns a
count of rows or a calculated value.
 ExecuteXMLReader: (SqlClient classes only) Obtains data from an SQL Server 2000
database using an XML stream. Returns an XML Reader object.

3. DataReader Class
The DataReader is used to retrieve data. It is used in conjunction with the Command
class to execute an SQL Select statement and then access the returned rows.

4. DataAdapter Class
The DataAdapter is used to connect DataSets to databases. The DataAdapter is most
useful when using data-bound controls in Windows Forms, but it can also be used to
provide an easy way to manage the connection between your application and the
underlying database tables, views and Stored Procedures.

SHASHI RAJ, BMSCW /Page 55


VB.Net Programming

5. DataSet Class
The DataSet is the heart of ADO.NET. The DataSet is essentially a collection of
DataTable objects. In turn each object contains a collection of DataColumn and
DataRow objects. The DataSet also contains a Relations collection that can be used to
define relations among Data Table Objects.

Features of ADO.NET :
 Interoperability- We know that XML documents are text-based formats. So, one can
edit and edit XML documents using standard text-editing tools. ADO.NET uses XML
in all data exchanges and for internal representation of data.
 Maintainability- ADO.NET is built around the idea of separation of data logic and
user interface. It means that we can create our application in independent layers.
 Programmability (Typed Programming): It is a programming style in which user
words are used to construct statements or evaluate expressions.
For example: If we want to select the “Marks” column from “Kawal” from the
“Student” table, the following is the way to do so:
DataSet.Student("Kawal").Marks;
 Performance- It uses disconnected data architecture which is easy to scale as it
reduces the load on the database. Everything is handled on the client-side, so it
improves performance.
 Scalability- It means meeting the needs of the growing number of clients, which
degrading performance. As it uses disconnected data access, applications do not retain
database lock connections for a longer time. Thus, it accommodates scalability by
encouraging programmers to conserve limited resources and allow users to access data
simultaneously.

Advantages of Using ADO.NET


ADO.NET has several advantages over Data Access Models and other components.
Some of these advantages are-

 Maintainability- Use N-tier application logic across additional tiers to maintain


several user requests at a time.
 Programmability- Strongly typed data and easy to write code because Microsoft
Visual Studio .NET framework provides statement completion.
 Performance- High performance due to connected mode.
 Scalability- Scalability of data is possible with storage conserving and web running
applications.
 Interoperability- XML is used to transmit data from a data source to a local in-
memory data location.

SHASHI RAJ, BMSCW /Page 56


VB.Net Programming

Difference Between DataSet, DataReader, DataAdapter, DataView

1. DataSet
Dataset is connection-less oriented, that means whenever we bind data from the database it
connects indirectly to the database and then disconnected. It has read/write access to data
tables. It supports both forward and backward scanning of data.
DataSet is a container of one or more DataTable. More often than not, it will just contain one
table, but if you do a query with multiple SELECT statements, the DataSet will contain a table
for each.
You have to be careful about how much data you pull into a DataSet because this is an in-
memory representation. You can Fill a DataSet using the Fill() method of a DataAdapter.

2. DataReader
DataReader is connection-oriented, that means whenever we bind data from the database it
must require a connection and after that disconnected from the connection. It has read-only
access, we can’t do any transaction on them. It supports forward-only scanning of data, in other
words, you can’t go backward.
DataReader fetches one row at a time so very less network cost as compare to DataSet(that
fetches all the rows at a time). It is scalable to any number of records, at least in terms of
memory pressure, since it only loads one record at a time. One typical way to get a DataReader
is by using the ExecuteReader() method of a DbCommand.

3. DataAdapter
DataAdapter is an ADO.NET Data Provider. DataAdapter can perform any SQL operations
like Insert, Update, Delete, Select in the Data Source by using SqlCommand to transmit
changes back to the database.
DataAdapter provides communication between the Dataset/DataTable and the Datasource. We
can use the DataAdapter in combination with the DataSet/DataTable objects. These two objects
combine to enable both data access and data manipulation capabilities.

4. DataView
Generally, we use DataView to filter and sort DataTable rows. So we can say that DataView is
like a virtual subset of a DataTable. This capability allows you to have two controls bound to
the same DataTable, but showing different versions of the data.
For example, one control may be bound to a DataView showing all of the rows in the table,
while a second may be configured to display only the rows that have been deleted from the
DataTable. The DataTable also has a DefaultView property that returns the default DataView for
the table.

SHASHI RAJ, BMSCW /Page 57


VB.Net Programming

Difference between ADO and ADO.NET :

What is a generics class?


A Generic class simply means that the items or functions in that class can be generalized
with the parameter(example T) to specify that we can add any type as a parameter in
place of T like Integer, Character, String, Double or any other user-defined type.
Example: Single type parameter.

Generics
A generic type is a single programming element that adapts to perform the same
functionality for a variety of data types. When you define a generic class or procedure,
you do not have to define a separate version for each data type for which you might want
to perform that functionality.

For example, you might want to create and use a queue class that operates on a specific
data type such as String.
You can declare such a class from System.Collections.Generic.Queue<T>, as the
following example shows.

Public stringQ As New System.Collections.Generic.Queue(Of String)

You can now use stringQ to work exclusively with String values. Because stringQ is
specific for String instead of being generalized for Object values, you do not have late
SHASHI RAJ, BMSCW /Page 58
VB.Net Programming
binding or type conversion. This saves execution time and reduces run-time errors.

Advantages of Generic Types

A generic type serves as a basis for declaring several different programming elements,
each of which operates on a specific data type. The alternatives to a generic type are:

1. A single type operating on the Object data type.


2. A set of type-specific versions of the type, each version individually coded and
operating on one specific data type such as String, Integer, or a user-defined type
such as customer.

A generic type has the following advantages over these alternatives:

 Type Safety. Generic types enforce compile-time type checking. Types based
on Object accept any data type, and you must write code to check whether an input
data type is acceptable. With generic types, the compiler can catch type mismatches
before run time.
 Performance. Generic types do not have to box and unbox data, because each one
is specialized for one data type. Operations based on Object must box input data
types to convert them to Object and unbox data destined for output. Boxing and
unboxing reduce performance.Types based on Object are also late-bound, which
means that accessing their members requires extra code at run time. This also
reduces performance.

SHASHI RAJ, BMSCW /Page 59


VB.Net Programming

 Code Consolidation. The code in a generic type has to be defined only once. A set
of type-specific versions of a type must replicate the same code in each version,
with the only difference being the specific data type for that version. With generic
types, the type-specific versions are all generated from the original generic type.
 Code Reuse. Code that does not depend on a particular data type can be reused
with various data types if it is generic. You can often reuse it even with a data type
that you did not originally predict.
 IDE Support. When you use a constructed type declared from a generic type, the
integrated development environment (IDE) can give you more support while you
are developing your code. For example, IntelliSense can show you the type-specific
options for an argument to a constructor or method.

Collections
Collection classes are specialized classes for data storage and retrieval. These classes
provide support for stacks, queues, lists, and hash tables. Most collection classes
implement the same interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to
elements and accessing a list of items on the basis of an index, etc. These classes create
collections of objects of the Object class, which is the base class for all data types in
VB.Net.
Various Collection Classes and Their Usage
The following are the various commonly used classes of
the System.Collection namespace. Click the following links to check their details.

Class Description and Usage

ArrayList It represents ordered collection of an object that can


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

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


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

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


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

SHASHI RAJ, BMSCW /Page 60


VB.Net Programming

items is always sorted by the key value.

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


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

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


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

BitArray It represents an array of the binary representation using the values


1 and 0.
It is used when you need to store the bits but do not know the
number of bits in advance. You can access items from the
BitArray collection by using an integer index, which starts from
zero.

What is Object-Oriented programming?

Object oriented programming is a concept that was created because of the need to overcome
the problems that were found with using structured programming techniques. While structured
programming uses an approach which is top down, OOP uses an approach which is bottom up.

Traditionally, programming has placed an emphasis on logic and actions. Object oriented
programming has taken a completely different direction, and will place an emphasis on objects
and information. With object oriented programming, a problem will be broken down into a
number of units. These units are called objects. The foundation of OOP is the fact that it will
place an emphasis on objects and classes. In Object-Oriented programming a program is
divided into object and these object can communicate with each other through functions.
Concepts of OOP:
 Objects
 Classes
 Data Abstraction
 Encapsulation
 Polymorphism
 Inheritance

Objects

Object is the basic unit of object-oriented programming. Objects are identified by its unique
name. An object represents a particular instance of a class. There can be more than one
instance of an object. Each instance of an object can hold its own relevant data. An Object is a
collection of data members and associated member functions also known as methods. When a
program is executed, objects interact with each other by sending messages.
SHASHI RAJ, BMSCW /Page 61
VB.Net Programming
Classes
Classes are data types based on which objects are created. Objects with similar properties and
methods are grouped together to form a Class. Thus a Class represent a set of individual
objects. Characteristics of an object are represented in a class as Properties. The actions that
can be performed by objects becomes functions of the class and is referred to as Methods.

Data Abstraction
Data Abstraction increases the power of programming language by creating user defined data
types. Data Abstraction also represents the needed information in the program without
presenting the details. Classes use the concept of abstraction and are defined as a list of
abstract attributes.

Encapsulation
Data Encapsulation combines data and functions into a single unit called Class. When using
Data Encapsulation, data is not accessed directly; it is only accessible through the functions
present inside the class. Data Encapsulation enables the important concept of data hiding
possible.

Polymorphism

Poly means many and morph means form. Thus, polymorphism refers to being able to use
many forms of a type without regard to the details. It is the characteristic of being able to
assign a different meaning specifically, to allow an entity such as a variable, a function, or an
object to have more than one form. In Polymorphism objects behaves differently depending on
their data types.

Inheritance

It is a primary feature of Object-Oriented Programming, just like encapsulation and


polymorphism, inheritance is an element of Object-Oriented Programming by which we
can derive the members of one class the "base class" for another class the "child class".
When we derive a class from a base class, the derived class will inherit all members of
the base class except constructors. With the help of inheritance we can create an object
that can reuse code. Once a method is defined in a super class, it is automatically
inherited by allsubclasses, they share a common set of properties.

Object-Oriented Programming allows classes to inherit commonly used state and


behavior from other classes. By using inheritance we can reduce the testing and
developing efforts. The behavior of the base class can be changed by writing code
in the derived class. This technique is called overriding. With the new implementations
of the derived class the inherited methods can also be override. Inheritance allows you
to build a hierarchy of related classes and to reuse functionality defined in existing
classes. All classes created with Visual Basic are inheritable by default. In Visual Basic
we use the Inherits keyword to inherit one class from another.

SHASHI RAJ, BMSCW /Page 62


VB.Net Programming

This code shows how to declare the inherit class:


Public Class Base
-

End Class

Public Class Derived


Inherits Base
'Derived class inherits the Base class
-

End Class

Derived classes inherit, and can extend the methods, properties and events of the base
class. With the use of inheritance we can use the variables, methods, properties, events
etc, from the base class and add more functionality to it in the derived class.
Imports System. Console
Module Module1

Sub Main()
Dim Obj As New Subclass()
WriteLine(Obj.sum())
Read()
End Sub

End Module

Public Class Superclass


'base class
Public X As Integer = 5
Public Y As Integer = 15

Public Function add() As Integer


Return X + Y
End Function

End Class

Public Class Subclass


Inherits Base
'derived class.Class Subclass inherited from class Superclass
Public Z As Integer = 25

Public Function sum() As Integer


'using the variables, function from superclass and adding more functionality
Return X + Y + Z
End Function

End Class

SHASHI RAJ, BMSCW /Page 63


VB.Net Programming

Custom Controls
Custom controls are deployed as individual assemblies. They are compiled into a
Dynamic Link Library (DLL) and used as any other ASP.NET server control. They
could be created in either of the following way:
 By deriving a custom control from an existing control
 By composing a new custom control combing two or more existing controls.
 By deriving from the base control class.

Crystal Reports in ASP.NET

Crystal Reports is the standard reporting tool for Visual Studio .NET used to display
data of presentation quality. You can display multiple-level totals, charts to analyze data,
and much more in Crystal Reports. Creating a Crystal Report requires minimal coding
since it is created in Designer interface. It is available as an integrated feature of
Microsoft Visual Studio .NET, Borland Delphi, and C#Builder.

Advantages of Crystal Reports

Some of the major advantages of using Crystal Reports are:

1. Rapid report development since the designer interface would ease the coding work
for the programmer.

2. Can extend it to complicated reports with interactive charts and enhance the
understanding of the business model

3. Exposes a report object model, can interact with other controls on the ASP.NET Web
form

4. Can programmatically export the reports into widely used formats like .pdf, .doc, .xls,
.html and .rtf

Implementation Models

Crystal Reports need database drivers to connect to the data source for accessing data.
Crystal Reports in .net support two methods to access data from a data source:

The Pull Method

When this model is used to access data from the data source, the database driver
directly retrieves the data from the data source. This model does not require the
developer to write code for creating a connection and retrieving data from the data
source. It is the Crystal report that manages the SQL commands for connecting by using
the specified driver
SHASHI RAJ, BMSCW /Page 64
VB.Net Programming

The Push Method

When this model is used to access data from data source, the developer writes the code
to connect to the data source and retrieve data. The data from the data source is cached
in dataset and multiple crystal reports accesses data from the dataset. The performance
can be optimized in this manner by using connection sharing and manually limiting the
number of records that are passed on to the report.

Crystal Reports Types

Crystal Report Designer can load reports that are included into the project as well as
those that are independent of the project.

Strongly-typed Report

When you add a report file into the project, it becomes a "strongly-typed" report. In this
case, you will have the advantage of directly creating an instance of the report object,
which could reduce a few lines of code, and cache it to improve performance. The
related .vb file, which is hidden, can be viewed using the editor's "show all files" icon in
the Solution Explorer.

Un-Typed Report

Those reports that are not included into the project are "un-typed" reports. In this case,
you will have to create an instance of the Crystal Report Engine's "ReportDocument "
object and manually load the report into it.

Understanding Scope and Accessibility of Variables

 Global Scope: A variable declared in the main VB.NET body. Accessible from
any part of the code and any kind of scope.
 Local Scope: A variable declared in a function or method. Due to encapsulation,
this variable can only be accessed in the function or method in which it was
declared in.

SHASHI RAJ, BMSCW /Page 65


VB.Net Programming

You can declare variables in three different settings in VB.NET classes. Each of one
these have its own protection level which determines what can access it.

 Public: Equivalent to the Global Scope. Can be accessed from any part of the
code.
 Private: Equivalent to the Local Scope. Can only be accessed within the method it
was declared in.
 Protected: Similar to private variables, with one key difference. If a child class
inherits a class with protected variables, the child class will be able to access these
protected variables.

Creating MDI parent and child

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

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

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

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

Let's create a program to display the multiple windows in the VB.NET Windows Forms.

Public Class Form1


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
IsMdiContainer = True
End Sub
Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MenuItem1ToolStripMenuItem.Click
Dim frm2 As New Form2
frm2.Show()
frm2.MdiParent = Me
End Sub

SHASHI RAJ, BMSCW /Page 66


VB.Net Programming

Private Sub MenuItem2ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MenuItem2ToolStripMenuItem.Click
Dim frm3 As New Form3
frm3.Show()
frm3.MdiParent = Me
End Sub
End Class
NOTE: If you want the MDI parent to auto-size the child form you can code like this.
form.MdiParent = Me
form.Dock = DockStyle.Fill
form.Show()

Built-in Functions
VB.Net has many built-in functions for manipulating text and carrying out mathematical
operations, as well as the ability to format data in both standard and user-defined styles. We start
by looking at two functions that are both frequently used and at the same time relatively easy to
get to grips with - the MsgBox() function and the InputBox() function. We will then look at some
of the more commonly-used string-handling and math functions

MsgBox() function
The MsgBox() function displays a message in a pop-up message box. The user is expected to
respond by clicking on a button in order to be able to continue. The format of the statement used
to invoke a message box is as follows:
returnVal = MsgBox (prompt, styleVal, title)

The prompt parameter is a string value (either a string literal or a string variable) that supplies
the message to be displayed. The styleVal parameter is either an integer style value from 0 to 5, or
a named constant that can be used instead of the corresponding integer value, that determines
which command buttons will appear on the message box. The title parameter is another string
literal or string variable that supplies the title for the message box.

The styles available are listed in the table below.

Message Box Styles


Named constant Buttons displayed

0 vbOkOnly OK

1 vbOkCancel OK, Cancel

2 vbAbortRetryIgnore Abort, Retry, Ignore

3 vbYesNoCancel Yes, No, Cancel

4 vbYesNo Yes, No

5 vbRetryCancel Retry, Cancel

SHASHI RAJ, BMSCW /Page 67


VB.Net Programming

InputBox() function

The InputBox() function displays a pop-up input box into which the user can type a message. The
user is expected to enter their message, then click on a button ("Cancel" or "OK") in order to
continue. The format of the statement used to invoke an input box is as follows:

returnString = InputBox (prompt, title, defaultText, xpos, ypos)

The returnString returned by the InputBox() function is the text entered by the user.
The prompt parameter is a text string (either a string literal or a string variable) that prompts the
user to enter some information. The title parameter is another string literal or string variable that
supplies the title for the input box. The defaultText parameter can be used to enter default content
in the input box (although it would probably be left blank in most cases).
The xpos and ypos parameters specify the x and y coordinates for the input box on screen.

String Functions

String Functions

Function Description
Mid (str, pos, n) Returns n characters from the text string referred to by str, starting
at character position pos.
Microsoft.VisualBasic.left Returns the n left-most characters from the text string referred to
(str, n) by str.
Microsoft.VisualBasic.right Returns the n right-most characters from the text string referred to
(str, n) by str.
Trim (str) Removes the white space (if any) at either end of the text string
referred to by str, and returns the result.
LTrim (str) Removes the white space (if any) at the left-hand end of the text
string referred to by str, and returns the result.
RTrim (str) Removes the white space (if any) at the right-hand end of the text
string referred to by str, and returns the result.
InStr (n, str1, str2) Looks for an occurrence of the substring str2 within the string str1,
starting at character position n. If successful, the function returns
the character position at which the substring is found (or zero if the
substring cannot be found).
UCase (str) Converts the string referred to by str to all upper-case characters,
and returns the result.
LCase (str) Converts the string referred to by str to all lower-case characters,
and returns the result.
Chr (charCode) Returns the ASCII character corresponding to the 8-bit character
code charCode (note – some characters are non-printing characters,
and will not be visible on screen).
Asc (character) Returns the 8-bit ASCII character code corresponding to character.

SHASHI RAJ, BMSCW /Page 68


VB.Net Programming

Mathematical functions

Maths Functions

Function Description
Math.Sqrt (n) Returns the square root of a number, n.
Math.Abs (n) Returns the absolute value of a number, n.
Math.Exp (n) Returns the exponential value of a number, n – i.e. e n.
Note: e = 2.71828182
Fix (n) Returns the integer part of a floating point number, n.
Int (n) Returns the integer part of a floating point number, n, for
positive numbers, or the next smallest integer value for
negative numbers.
Math.Log (n) Returns the natural logarithm of a number, n.
Rnd () Returns a randomly generated value between 0 and 1.
Round (n,m) Rounds a number, n, up (or down) to m decimal places.
Example for Mathematical functions :
Private Sub MathClass_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer
i = Math.Pow(5, 5)
MessageBox.Show("5 to the power= " & i)

i = Math.Sqrt(5)
MessageBox.Show("squre root of 5= " & i)

i = Math.Round(5.68743)
MessageBox.Show("round figure of 5.68743= " & i)

i = Math.Min(4, 7)
MessageBox.Show("minimum value in 4 and 7= " & i)

Dim j As Double

j = Math.Log(15)
MessageBox.Show("Log value of 15 = " & j)

j = Math.Sin(90)
MessageBox.Show("sin 90 = " & j)

Dim x As Integer = 511


Dim y As Integer = 50
Dim Value As Integer
Dim Remainder As Integer
Value = Math.DivRem(x, y, Remainder)
MessageBox.Show("value is = " & Value & " and reminder is = " & Remainder)

End Sub

SHASHI RAJ, BMSCW /Page 69

You might also like