Unit.3 Web Programming With V.B

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

web programming with V.

B
Visual Basic .NET (VB.NET) is an object-oriented computer programming language
implemented on the .NET Framework. Although it is an evolution of classic Visual Basic
language, it is not backwards-compatible with VB6, and any code written in the old version does
not compile under VB.NET.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts.
Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long,
String, Boolean, etc.) and user-defined types, events, and even assemblies. All objects inherits
from the base class Object.
VB.NET is implemented by Microsoft's .NET framework. Therefore, it has full access to all the
libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the open-
source alternative to .NET, not only under Windows, but even Linux or Mac OSX.
The following reasons make VB.Net a widely used professional language −
 Modern, general purpose.
 Object oriented.
 Component oriented.
 Easy to learn.
 Structured language.
 It produces efficient programs.
 It can be compiled on a variety of computer platforms.
 Part of .Net Framework.

Strong Programming Features VB.Net


VB.Net has numerous strong programming features that make it endearing to multitude of
programmers worldwide. Let us mention some of these features −
 Boolean Conditions
 Automatic Garbage Collection
 Standard Library
 Assembly Versioning
 Properties and Events
 Delegates and Events Management
 Easy-to-use Generics
 Indexers
 Conditional Compilation
 Simple Multithreading

VB.Net - Environment Setup


In this chapter, we will discuss the tools available for creating VB.Net applications.
We have already mentioned that VB.Net is part of .Net framework and used for writing .Net
applications. Therefore before discussing the available tools for running a VB.Net program, let
us understand how VB.Net relates to the .Net framework.

The .Net Framework


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)
 LINQ
For the jobs each of these components perform, please see ASP.Net - Introduction, and for
details of each component, please consult Microsoft's documentation.

Integrated Development Environment (IDE) For VB.Net


Microsoft provides the following development tools for VB.Net programming −
 Visual Studio 2010 (VS)
 Visual Basic 2010 Express (VBE)
 Visual Web Developer
The last two are free. Using these tools, you can write all kinds of VB.Net programs from simple
command-line applications to more complex applications. Visual Basic Express and Visual Web
Developer Express edition are trimmed down versions of Visual Studio and has the same look
and feel. They retain most features of Visual Studio. In this tutorial, we have used Visual Basic
2010 Express and Visual Web Developer (for the web programming chapter).
You can download it from here. It gets automatically installed in your machine. Please note that
you need an active internet connection for installing the express edition.

Writing VB.Net Programs on Linux or Mac OS


Although the.NET Framework runs on the Windows operating system, there are some alternative
versions that work on other operating systems. Mono is an open-source version of the .NET
Framework which includes a Visual Basic compiler and runs on several operating systems,
including various flavors of Linux and Mac OS. The most recent version is VB 2012.
The stated purpose of Mono is not only to be able to run Microsoft .NET applications cross-
platform, but also to bring better development tools to Linux developers. Mono can be run on
many operating systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris and
UNIX.

VB.Net - Program Structure

Before we study basic building blocks of the VB.Net programming language, let us look a bare
minimum VB.Net program structure so that we can take it as a reference in upcoming chapters.

VB.Net Hello World Example


A VB.Net program basically consists of the following parts −
 Namespace declaration
 A class or module
 One or more procedures
 Variables
 The Main procedure
 Statements & Expressions
 Comments
Let us look at a simple code that would print the words "Hello World" −

Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Hello, World!
Let us look various parts of the above program −
 The first line of the program Imports System is used to include the System namespace in
the program.
 The next line has a Module declaration, the module Module1. VB.Net is completely
object oriented, so every program must contain a module of a class that contains the data
and procedures that your program uses.
 Classes or Modules generally would contain more than one procedure. Procedures contain
the executable code, or in other words, they define the behavior of the class. A procedure
could be any of the following −
o Function
o Sub
o Operator
o Get
o Set
o AddHandler
o RemoveHandler
o RaiseEvent
 The next line( 'This program) will be ignored by the compiler and it has been put to add
additional comments in the program.
 The next line defines the Main procedure, which is the entry point for all VB.Net
programs. The Main procedure states what the module or class will do when executed.
 The Main procedure specifies its behavior with the statement
Console.WriteLine("Hello World") WriteLine is a method of the Console class defined
in the System namespace. This statement causes the message "Hello, World!" to be
displayed on the screen.
 The last line Console.ReadKey() is for the VS.NET Users. This will prevent the screen
from running and closing quickly when the program is launched from Visual Studio
.NET.

Compile & Execute VB.Net Program


If you are using Visual Studio.Net IDE, take the following steps −
 Start Visual Studio.
 On the menu bar, choose File → New → Project.
 Choose Visual Basic from templates
 Choose Console Application.
 Specify a name and location for your project using the Browse button, and then choose
the OK button.
 The new project appears in Solution Explorer.
 Write code in the Code Editor.
 Click the Run button or the F5 key to run the project. A Command Prompt window
appears that contains the line Hello World.
You can compile a VB.Net program by using the command line instead of the Visual Studio IDE

 Open a text editor and add the above mentioned code.
 Save the file as helloworld.vb
 Open the command prompt tool and go to the directory where you saved the file.
 Type vbc helloworld.vb and press enter to compile your code.
 If there are no errors in your code the command prompt will take you to the next line and
would generate helloworld.exe executable file.
 Next, type helloworld to execute your program.
 You will be able to see "Hello World" printed on the screen.

VB.Net - Basic Syntax

VB.Net is an object-oriented programming language. In Object-Oriented Programming


methodology, a program consists of various objects that interact with each other by means of
actions. The actions that an object may take are called methods. Objects of the same kind are
said to have the same type or, more often, are said to be in the same class.
When we consider a VB.Net program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods and instance variables mean.
 Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors - wagging, barking, eating, etc. An object is an instance of a
class.
 Class − A class can be defined as a template/blueprint that describes the behaviors/states
that objects of its type support.
 Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
 Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item.
The basic rules for naming classes in VB.Net are as follows −
 A name must begin with a letter that could be followed by a sequence of letters, digits (0 -
9) or underscore. The first character in an identifier cannot be a digit.
 It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : "
' / and \. However, an underscore ( _ ) can be used.
 It should not be a reserved keyword.

VB.Net - 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 −

Data Type Storage Allocation Value Range

Boolean Depends on implementing platform True or False

Byte 1 byte 0 through 255 (unsigned)

Char 2 bytes 0 through 65535 (unsigned)

Date 8 bytes 0:00:00 (midnight) on January 1, 0001


through 11:59:59 PM on December 31, 9999

Decimal 16 bytes 0 through +/-


79,228,162,514,264,337,593,543,950,335 (+/-
7.9...E+28) with no decimal point; 0 through
+/-7.9228162514264337593543950335 with
28 places to the right of the decimal

Double 8 bytes
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative
values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive
values

Integer 4 bytes -2,147,483,648 through 2,147,483,647


(signed)

Long 8 bytes -9,223,372,036,854,775,808 through


9,223,372,036,854,775,807(signed)

Object Any type can be stored in a variable of type


4 bytes on 32-bit platform
Object
8 bytes on 64-bit platform

SByte 1 byte -128 through 127 (signed)

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

Single 4 bytes
-3.4028235E+38 through -1.401298E-45 for
negative values;
1.401298E-45 through 3.4028235E+38 for
positive values

String Depends on implementing platform 0 to approximately 2 billion Unicode


characters

UInteger 4 bytes 0 through 4,294,967,295 (unsigned)

ULong 8 bytes 0 through 18,446,744,073,709,551,615


(unsigned)
User-Defined Depends on implementing platform Each member of the structure has a range
determined by its data type and independent
of the ranges of the other members

UShort 2 bytes 0 through 65,535 (unsigned)

Example
The following example demonstrates use of some of the types −
Live Demo

Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean

b=1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"

If ScriptEngine = "VB" Then


bl = True
Else
bl = False
End If

If bl Then
'the oath taking
Console.Write(c & " and," & s & vbCrLf)
Console.WriteLine("declaring on the day of: {0}", da)
Console.WriteLine("We will learn VB.Net seriously")
Console.WriteLine("Lets see what happens to the floating point variables:")
Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
End If
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously
Lets see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346

VB.Net - Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in VB.Net has a specific type, which determines the size and layout of the variable's memory; the range of
values that can be stored within that memory; and the set of operations that can be applied to the variable.

We have already discussed various data types. The basic value types provided in VB.Net can be
categorized as −

Type Example

Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char

Floating point types Single and Double

Decimal types Decimal

Boolean types True or False values, as assigned

Date types Date

VB.Net also allows defining other value types of variable like Enum and reference types of
variables like Class. We will discuss date types and Classes in subsequent chapters.

Variable Declaration in VB.Net


The Dim statement is used for variable declaration and storage allocation for one or more
variables. The Dim statement is used at module, class, structure, procedure or block level.
Syntax for variable declaration in VB.Net is −
[ < attributelist > ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]]
[ ReadOnly ] Dim [ WithEvents ] variablelist
Where,
 attributelist is a list of attributes that apply to the variable. Optional.
 accessmodifier defines the access levels of the variables, it has values as - Public,
Protected, Friend, Protected Friend and Private. Optional.
 Shared declares a shared variable, which is not associated with any specific instance of a
class or structure, rather available to all the instances of the class or structure. Optional.
 Shadows indicate that the variable re-declares and hides an identically named element, or
set of overloaded elements, in a base class. Optional.
 Static indicates that the variable will retain its value, even when the after termination of
the procedure in which it is declared. Optional.
 ReadOnly means the variable can be read, but not written. Optional.
 WithEvents specifies that the variable is used to respond to events raised by the instance
assigned to the variable. Optional.
 Variablelist provides the list of variables declared.
Each variable in the variable list has the following syntax and parts −
variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ = initializer ]
Where,
 variablename − is the name of the variable
 boundslist − optional. It provides list of bounds of each dimension of an array variable.
 New − optional. It creates a new instance of the class when the Dim statement runs.
 datatype − Required if Option Strict is On. It specifies the data type of the variable.
 initializer − Optional if New is not specified. Expression that is evaluated and assigned to
the variable when it is created.
Some valid variable declarations along with their definition are shown here −
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
Dim count1, count2 As Integer
Dim status As Boolean
Dim exitButton As New System.Windows.Forms.Button
Dim lastTime, nextTime As Date

Variable Initialization in VB.Net


Variables are initialized (assigned a value) with an equal sign followed by a constant expression.
The general form of initialization is −
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
You can initialize a variable at the time of declaration as follows −
Dim StudentID As Integer = 100
Dim StudentName As String = "Bill Smith"

Example
Try the following example which makes use of various types of variables −

Module variablesNdataypes
Sub Main()
Dim a As Short
Dim b As Integer
Dim c As Double

a = 10
b = 20
c=a+b
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30

Accepting Values from User


The Console class in the System namespace provides a function ReadLine for accepting input
from the user and store it into a variable. For example,
Dim message As String
message = Console.ReadLine
The following example demonstrates it −
Module variablesNdataypes

Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result (assume the user
inputs Hello World) −
Enter message: Hello World
Your Message: Hello World

Lvalues and Rvalues


There are two kinds of expressions −
 lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand
side of an assignment.
 rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of
an assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals
are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a
valid statement −
Dim g As Integer = 20
But following is not a valid statement and would generate compile-time error −
20 = g

VB.Net - Statements

A statement is a complete instruction in Visual Basic programs. It may contain keywords, operators,
variables, literal values, constants and expressions.

Statements could be categorized as −


 Declaration statements − these are the statements where you name a variable, constant,
or procedure, and can also specify a data type.
 Executable statements − these are the statements, which initiate actions. These
statements can call a method or function, loop or branch through blocks of code or assign
values or expression to a variable or constant. In the last case, it is called an Assignment
statement.
Declaration Statements
The declaration statements are used to name and define procedures, variables, properties, arrays,
and constants. When you declare a programming element, you can also define its data type,
access level, and scope.
The programming elements you may declare include variables, constants, enumerations, classes,
structures, modules, interfaces, procedures, procedure parameters, function returns, external
procedure references, operators, properties, events, and delegates.
Following are the declaration statements in VB.Net −

Sr.No Statements and Description Example

1 Dim number As
Dim Statement
Integer
Declares and allocates storage space for one or more variables. Dim quantity As
Integer = 100
Dim message As
String = "Hello!"

2 Const maximum As
Const Statement
Long = 1000
Declares and defines one or more constants. Const
naturalLogBase As
Object
=
CDec(2.7182818284)

3 Enum
Enum Statement
CoffeeMugSize
Declares an enumeration and defines the values of its members. Jumbo
ExtraLarge
Large
Medium
Small
End Enum

4 Class Box
Class Statement
Public length As
Declares the name of a class and introduces the definition of the Double
Public breadth As
variables, properties, events, and procedures that the class
Double
comprises. Public height As
Double
End Class

5 Structure Box
Structure Statement
Public length As
Double
Declares the name of a structure and introduces the definition of Public breadth As
the variables, properties, events, and procedures that the structure Double
Public height As
comprises. Double
End Structure

6 Public Module
Module Statement
myModule
Declares the name of a module and introduces the definition of the Sub Main()
Dim user As String =
variables, properties, events, and procedures that the module
InputBox("What is
comprises. your name?")
MsgBox("User name
is" & user)
End Sub
End Module

7 Public Interface
Interface Statement
MyInterface
Declares the name of an interface and introduces the definitions of Sub doSomething()
End Interface
the members that the interface comprises.

8 Function myFunction
Function Statement
(ByVal n As Integer)
Declares the name, parameters, and code that define a Function As Double
Return 5.87 * n
procedure.
End Function

9 Sub mySub(ByVal s
Sub Statement
As String)
Declares the name, parameters, and code that define a Sub Return
End Sub
procedure.

10 Declare Function
Declare Statement
getUserName
Declares a reference to a procedure implemented in an external Lib "advapi32.dll"
Alias
file.
"GetUserNameA"
(
ByVal lpBuffer As
String,
ByRef nSize As
Integer) As Integer

11 Public Shared
Operator Statement
Operator +
Declares the operator symbol, operands, and code that define an (ByVal x As obj,
ByVal y As obj) As
operator procedure on a class or structure.
obj
Dim r As New obj
' implemention code
for r = x + y
Return r
End Operator

12 ReadOnly Property
Property Statement
quote() As String
Declares the name of a property, and the property procedures used Get
Return
to store and retrieve the value of the property.
quoteString
End Get
End Property

13 Public Event
Event Statement
Finished()
Declares a user-defined event.

14 Delegate Function
Delegate Statement
MathOperator(
Used to declare a delegate. ByVal x As
Double,
ByVal y As Double
) As Double

Executable Statements
An executable statement performs an action. Statements calling a procedure, branching to
another place in the code, looping through several statements, or evaluating an expression are
executable statements. An assignment statement is a special case of an executable statement.
Example
The following example demonstrates a decision making statement −

Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 10

' check the boolean condition using if statement '


If (a < 20) Then
' if condition is true then print the following '
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a is less than 20;
value of a is : 10

VB.Net - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
VB.Net is rich in built-in operators and provides following types of commonly used operators −

 Arithmetic Operators
 Comparison Operators
 Logical/Bitwise Operators
 Bit Shift Operators
 Assignment Operators
 Miscellaneous Operators
This tutorial will explain the most commonly used operators.

Arithmetic Operators
Following table shows all the arithmetic operators supported by VB.Net. Assume
variable A holds 2 and variable B holds 7, then −
Show Examples

Operator Description Example

^ Raises one operand to the power of another B^A will give 49

+ Adds two operands A + B will give 9

- Subtracts second operand from the first A - B will give -5

* Multiplies both operands A * B will give 14

/ Divides one operand by another and returns a floating point result B / A will give 3.5
\ Divides one operand by another and returns an integer result B \ A will give 3

MOD Modulus Operator and remainder of after an integer division B MOD A will
give 1

Comparison Operators
Following table shows all the comparison operators supported by VB.Net. Assume
variable A holds 10 and variable B holds 20, then −
Show Examples

Operator Description Example

= Checks if the values of two operands are equal or not; if yes, then condition (A = B)
becomes true. is not
true.

<> Checks if the values of two operands are equal or not; if values are not (A <> B)
equal, then condition becomes true. is true.

> Checks if the value of left operand is greater than the value of right (A > B)
operand; if yes, then condition becomes true. is not
true.

< Checks if the value of left operand is less than the value of right operand; if (A < B)
yes, then condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand; if yes, then condition becomes true. is not
true.

<= Checks if the value of left operand is less than or equal to the value of right (A <= B)
operand; if yes, then condition becomes true. is true.

Apart from the above, VB.Net provides three more comparison operators, which we will be
using in forthcoming chapters; however, we give a brief description here.
 Is Operator − It compares two object reference variables and determines if two object
references refer to the same object without performing value comparisons. If object1 and
object2 both refer to the exact same object instance, result is True; otherwise, result is
False.
 IsNot Operator − It also compares two object reference variables and determines if two
object references refer to different objects. If object1 and object2 both refer to the exact
same object instance, result is False; otherwise, result is True.
 Like Operator − It compares a string against a pattern.

Logical/Bitwise Operators
Following table shows all the logical operators supported by VB.Net. Assume variable A holds
Boolean value True and variable B holds Boolean value False, then −
Show Examples

Operator Description Example

And It is the logical as well as bitwise AND operator. If both the operands are (A And
true, then condition becomes true. This operator does not perform short- B) is
circuiting, i.e., it evaluates both the expressions. False.

Or It is the logical as well as bitwise OR operator. If any of the two operands is (A Or B)


true, then condition becomes true. This operator does not perform short- is True.
circuiting, i.e., it evaluates both the expressions.

Not It is the logical as well as bitwise NOT operator. Use to reverses the logical Not(A
state of its operand. If a condition is true, then Logical NOT operator will And B)
make false. is True.

Xor It is the logical as well as bitwise Logical Exclusive OR operator. It returns A Xor B
True if both expressions are True or both expressions are False; otherwise it is True.
returns False. This operator does not perform short-circuiting, it always
evaluates both expressions and there is no short-circuiting counterpart of
this operator.

AndAlso It is the logical AND operator. It works only on Boolean data. It performs (A
short-circuiting. AndAlso
B) is
False.
OrElse It is the logical OR operator. It works only on Boolean data. It performs (A
short-circuiting. OrElse
B) is
True.

IsFalse It determines whether an expression is False.

IsTrue It determines whether an expression is True.

Bit Shift Operators


We have already discussed the bitwise operators. The bit shift operators perform the shift
operations on binary values. Before coming into the bit shift operators, let us understand the bit
operations.
Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &, |, and ^
are as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
We have seen that the Bitwise operators supported by VB.Net are And, Or, Xor and Not. The Bit
shift operators are >> and << for left shift and right shift, respectively.
Assume that the variable A holds 60 and variable B holds 13, then −
Show Examples

Operator Description Example

And Bitwise AND Operator copies a bit to the result if it exists in both (A AND B)
operands. will give
12, which is
0000 1100

Or Binary OR Operator copies a bit if it exists in either operand. (A Or B)


will give
61, which is
0011 1101

Xor Binary XOR Operator copies the bit if it is set in one operand but not (A Xor B)
both. will give
49, which is
0011 0001

Not Binary Ones Complement Operator is unary and has the effect of (Not A )
'flipping' bits. will give -
61, which is
1100 0011
in 2's
complement
form due to
a signed
binary
number.

<< Binary Left Shift Operator. The left operands value is moved left by the A << 2 will
number of bits specified by the right operand. give 240,
which is
1111 0000
>> Binary Right Shift Operator. The left operands value is moved right by A >> 2 will
the number of bits specified by the right operand. give 15,
which is
0000 1111

Assignment Operators
There are following assignment operators supported by VB.Net −
Show Examples

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to C=A+
left side operand B will
assign
value of
A+B
into C

+= Add AND assignment operator, It adds right operand to the left operand C += A is
and assigns the result to left operand equivalent
to C = C
+A

-= Subtract AND assignment operator, It subtracts right operand from the left C -= A is
operand and assigns the result to left operand equivalent
to C = C -
A

*= Multiply AND assignment operator, It multiplies right operand with the C *= A is


left operand and assigns the result to left operand equivalent
to C = C
*A

/= Divide AND assignment operator, It divides left operand with the right C /= A is
operand and assigns the result to left operand (floating point division) equivalent
to C = C /
A

\= Divide AND assignment operator, It divides left operand with the right C \= A is
operand and assigns the result to left operand (Integer division) equivalent
to C = C
\A

^= Exponentiation and assignment operator. It raises the left operand to the C^=A is
power of the right operand and assigns the result to left operand. equivalent
to C = C ^
A

<<= Left shift AND assignment operator C <<= 2


is same as
C = C <<
2

>>= Right shift AND assignment operator C >>= 2


is same as
C = C >>
2

&= Concatenates a String expression to a String variable or property and


Str1 &=
assigns the result to the variable or property. Str2 is
same as
Str1 =
Str1 &
Str2

Miscellaneous Operators
There are few other important operators supported by VB.Net.
Show Examples

Operator Description Example


AddressOf Returns the address of a procedure. AddHandler Button1.Click,
AddressOf Button1_Click

Await It is applied to an operand in an asynchronous


method or lambda expression to suspend Dim result As res
= Await
execution of the method until the awaited task AsyncMethodThatReturnsResult()
completes. Await AsyncMethod()

GetType It returns a Type object for the specified type. MsgBox(GetType(Integer).ToString())


The Type object provides information about the
type such as its properties, methods, and events.

Function It declares the parameters and code that define a Dim add5 = Function(num As
Expression function lambda expression. Integer) num + 5
'prints 10
Console.WriteLine(add5(5))

If It uses short-circuit evaluation to conditionally Dim num = 5


return one of two values. The If operator can be Console.WriteLine(If(num >= 0,
"Positive", "Negative"))
called with three arguments or with two
arguments.

Operators Precedence in VB.Net


Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples

Operator Precedence

Await Highest

Exponentiation (^)
Unary identity and negation (+, -)

Multiplication and floating-point division (*, /)

Integer division (\)

Modulus arithmetic (Mod)

Addition and subtraction (+, -)

Arithmetic bit shift (<<, >>)

All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)

Negation (Not)

Conjunction (And, AndAlso)

Inclusive disjunction (Or, OrElse)

Exclusive disjunction (Xor) Lowest

VB.Net - Decision Making

More Detail

Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages −

VB.Net provides the following types of decision making statements. Click the following links to
check their details.

Statement Description

If ... Then statement An If...Then statement consists of a boolean expression


followed by one or more statements.

If...Then...Else statement An If...Then statement can be followed by an optional Else


statement, which executes when the boolean expression is
false.

You can use one If or Else if statement inside another If or Else


nested If statements
if statement(s).

Select Case statement A Select Case statement allows a variable to be tested for
equality against a list of values.

nested Select Case statements You can use one select case statement inside another select
case statement(s).

VB.Net - Loops

There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on.

Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

VB.Net provides following types of loops to handle looping requirements. Click the following
links to check their details.

Loop Type Description

Do Loop It repeats the enclosed block of statements while a Boolean


condition is True or until the condition becomes True. It could be
terminated at any time with the Exit Do statement.

For...Next It repeats a group of statements a specified number of times and a


loop index counts the number of loop iterations as the loop
executes.

It repeats a group of statements for each element in a collection. This


For Each...Next
loop is used for accessing and manipulating all elements in an array
or a VB.Net collection.

While... End While It executes a series of statements as long as a given condition is


True.

With... End With It is not exactly a looping construct. It executes a series of


statements that repeatedly refer to a single object or structure.

Nested loops You can use one or more loops inside any another While, For or
Do loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
VB.Net provides the following control statements. Click the following links to check their
details.

Control Statement Description

Exit statement Terminates the loop or select case statement and transfers
execution to the statement immediately following the loop or
select case.

Continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.

GoTo statement Transfers control to the labeled statement. Though it is not advised
to use GoTo statement in your program.

VB.Net - Arrays

An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables of the same
type.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.

Creating Arrays in VB.Net


To declare an array in VB.Net, you use the Dim statement. For example,
Dim intData(30) ' an array of 31 elements
Dim strData(20) As String ' an array of 21 strings
Dim twoDarray(10, 20) As Integer 'a two dimensional array of integers
Dim ranges(10, 100) 'a two dimensional array
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _
"Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
The elements in an array can be stored and accessed by using the index of the array. The
following program demonstrates this −

Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '

For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
Element(9) = 109
Element(10) = 110

Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the
program. You can declare a dynamic array using the ReDim statement.
Syntax for ReDim statement −
ReDim [Preserve] arrayname(subscripts)
Where,
 The Preserve keyword helps to preserve the data in an existing array, when you resize it.
 arrayname is the name of the array to re-dimension.
 subscripts specifies the new dimension.
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90

ReDim Preserve marks(10)


marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75

For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0

Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular
arrays.
You can declare a 2-dimensional array of strings as −
Dim twoDStringArray(10, 20) As String
or, a 3-dimensional array of Integer variables −
Dim threeDIntArray(10, 10, 10) As Integer
The following program demonstrates creating and using a 2-dimensional array –

Module arrayApl

Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a jagged array
named scores of Integers −
Dim scores As Integer()() = New Integer(5)(){}
The following example illustrates using a jagged array −

Module arrayApl
Sub Main()
'a jagged array of 5 array of integers
Dim a As Integer()() = New Integer(4)() {}
a(0) = New Integer() {0, 0}
a(1) = New Integer() {1, 2}
a(2) = New Integer() {2, 4}
a(3) = New Integer() {3, 6}
a(4) = New Integer() {4, 8}
Dim i, j As Integer
' output each array element's value

For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i)(j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

The Array Class


The Array class is the base class for all the arrays in VB.Net. It is defined in the System
namespace. The Array class provides various properties and methods to work with arrays.
Properties of the Array Class
The following table provides some of the most commonly used properties of the Array class −

Sr.No Property Name & Description

1
IsFixedSize
Gets a value indicating whether the Array has a fixed size.

2
IsReadOnly
Gets a value indicating whether the Array is read-only.

3
Length
Gets a 32-bit integer that represents the total number of elements in all the dimensions
of the Array.

4
LongLength
Gets a 64-bit integer that represents the total number of elements in all the dimensions
of the Array.

5
Rank
Gets the rank (number of dimensions) of the Array.

Methods of the Array Class


The following table provides some of the most commonly used methods of the Array class −

Sr.No Method Name & Description

1
Public Shared Sub Clear (array As Array, index As Integer, length As Integer)
Sets a range of elements in the Array to zero, to false, or to null, depending on the
element type.

2
Public Shared Sub Copy (sourceArray As Array, destinationArray As Array,
length As Integer)
Copies a range of elements from an Array starting at the first element and pastes them
into another Array starting at the first element. The length is specified as a 32-bit
integer.

3
Public Sub CopyTo (array As Array, index As Integer)
Copies all the elements of the current one-dimensional Array to the specified one-
dimensional Array starting at the specified destination Array index. The index is
specified as a 32-bit integer.

4
Public Function GetLength (dimension As Integer) As Integer
Gets a 32-bit integer that represents the number of elements in the specified dimension
of the Array.

5
Public Function GetLongLength (dimension As Integer) As Long
Gets a 64-bit integer that represents the number of elements in the specified dimension
of the Array.

6
Public Function GetLowerBound (dimension As Integer) As Integer
Gets the lower bound of the specified dimension in the Array.

7
Public Function GetType As Type
Gets the Type of the current instance (Inherited from Object).

8
Public Function GetUpperBound (dimension As Integer) As Integer
Gets the upper bound of the specified dimension in the Array.

9
Public Function GetValue (index As Integer) As Object
Gets the value at the specified position in the one-dimensional Array. The index is
specified as a 32-bit integer.

10
Public Shared Function IndexOf (array As Array,value As Object) As Integer
Searches for the specified object and returns the index of the first occurrence within the
entire one-dimensional Array.

11
Public Shared Sub Reverse (array As Array)
Reverses the sequence of the elements in the entire one-dimensional Array.

12
Public Sub SetValue (value As Object, index As Integer)
Sets a value to the element at the specified position in the one-dimensional Array. The
index is specified as a 32-bit integer.

13
Public Shared Sub Sort (array As Array)
Sorts the elements in an entire one-dimensional Array using the IComparable
implementation of each element of the Array.

14
Public Overridable Function ToString As String
Returns a string that represents the current object (Inherited from Object).

For complete list of Array class properties and methods, please consult Microsoft documentation.
Example
The following program demonstrates use of some of the methods of the Array class:
Module arrayApl

Sub Main()
Dim list As Integer() = {34, 72, 13, 44, 25, 30, 10}
Dim temp As Integer() = list
Dim i As Integer
Console.Write("Original Array: ")

For Each i In list


Console.Write("{0} ", i)
Next i
Console.WriteLine()
' reverse the array
Array.Reverse(temp)
Console.Write("Reversed Array: ")

For Each i In temp


Console.Write("{0} ", i)
Next i
Console.WriteLine()
'sort the array
Array.Sort(list)
Console.Write("Sorted Array: ")

For Each i In list


Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72

VB.Net - 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 Useage

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

VB.Net - Functions

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.

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

Example
Following code snippet shows a function FindMax that takes two integer values and returns the
larger of the two.
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1
Else
result = num2
End If
FindMax = result
End Function

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
The following example demonstrates using the FindMax function −
Live Demo

Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num1 > num2) Then


result = num1
Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer = 200
Dim res As Integer

res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Max value is : 200

Recursive Function
A function can call itself. This is known as recursion. Following is an example that calculates
factorial for a given number using a recursive function −
Live Demo

Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer

If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320

Param Arrays
At times, while declaring a function or sub procedure, you are not sure of the number of
arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into help at
these times.
The following example demonstrates this −
Live Demo

Module myparamfunc
Function AddElements(ParamArray arr As Integer()) As Integer
Dim sum As Integer = 0
Dim i As Integer = 0

For Each i In arr


sum += i
Next i
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = AddElements(512, 720, 250, 567, 889)
Console.WriteLine("The sum is: {0}", sum)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
The sum is: 2938

Passing Arrays as Function Arguments


You can pass an array as a function argument in VB.Net. The following example demonstrates
this −

Module arrayParameter
Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double
'local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0

For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Return avg
End Function
Sub Main()
' an int array with 5 elements '
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
'pass pointer to the array as an argument
avg = getAverage(balance, 5)
' output the returned value '
Console.WriteLine("Average value is: {0} ", avg)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Average value is: 214.4

VB.Net - Classes & Objects

More Detail

When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but
it does define what the class name means, that is, what an object of the class will consist of and what
operations can be performed on such an object.

Objects are instances of a class. The methods and variables that constitute a class are called
members of the class.

Class Definition
A class definition starts with the keyword Class followed by the class name; and the class body,
ended by the End Class statement. Following is the general form of a class definition −
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
 attributelist is a list of attributes that apply to the class. Optional.
 accessmodifier defines the access levels of the class, it has values as - Public, Protected,
Friend, Protected Friend and Private. Optional.
 Shadows indicate that the variable re-declares and hides an identically named element, or
set of overloaded elements, in a base class. Optional.
 MustInherit specifies that the class can be used only as a base class and that you cannot
create an object directly from it, i.e., an abstract class. Optional.
 NotInheritable specifies that the class cannot be used as a base class.
 Partial indicates a partial definition of the class.
 Inherits specifies the base class it is inheriting from.
 Implements specifies the interfaces the class is inheriting from.
The following example demonstrates a Box class, with three data members, length, breadth and
height −

Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here

' box 1 specification


Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0

' box 2 specification


Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0

'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)

'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560

Member Functions and Encapsulation


A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable. It operates on any object of the class of which it is a member
and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept private
to implement encapsulation. These variables can only be accessed using the public member
functions.
Let us put above concepts to set and get the value of different class members in a class −

Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public Sub setLength(ByVal len As Double)
length = len
End Sub

Public Sub setBreadth(ByVal bre As Double)


breadth = bre
End Sub

Public Sub setHeight(ByVal hei As Double)


height = hei
End Sub

Public Function getVolume() As Double


Return length * breadth * height
End Function
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here

' box 1 specification


Box1.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)

'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)

' volume of box 1


volume = Box1.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)

'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560

Constructors and Destructors


A class constructor is a special member Sub of a class that is executed whenever we create new
objects of that class. A constructor has the name New and it does not have any return type.
Following program explains the concept of constructor –
Class Line

Private length As Double ' Length of a line


Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
A default constructor does not have any parameter, but if you need, a constructor can have
parameters. Such constructors are called parameterized constructors. This technique helps you
to assign initial value to an object at the time of its creation as shown in the following example −

Class Line
Private length As Double ' Length of a line
Public Sub New(ByVal len As Double) 'parameterised constructor
Console.WriteLine("Object is being created, length = {0}", len)
length = len
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub

Public Function getLength() As Double


Return length
End Function
Shared Sub Main()
Dim line As Line = New Line(10.0)
Console.WriteLine("Length of line set by constructor : {0}", line.getLength())
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line set by setLength : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Object is being created, length = 10
Length of line set by constructor : 10
Length of line set by setLength : 6
A destructor is a special member Sub of a class that is executed whenever an object of its class
goes out of scope.
A destructor has the name Finalize and it can neither return a value nor can it take any
parameters. Destructor can be very useful for releasing resources before coming out of the
program like closing files, releasing memories, etc.
Destructors cannot be inherited or overloaded.
Following example explains the concept of destructor −

Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub

Protected Overrides Sub Finalize() ' destructor


Console.WriteLine("Object is being deleted")
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function

Shared Sub Main()


Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
Object is being deleted

Shared Members of a VB.Net Class


We can define class members as static using the Shared keyword. When we declare a member of
a class as Shared, it means no matter how many objects of the class are created, there is only one
copy of the member.
The keyword Shared implies that only one instance of the member exists for a class. Shared
variables are used for defining constants because their values can be retrieved by invoking the
class without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You can also
initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared
variables. The Shared functions exist even before the object is created.
The following example demonstrates the use of shared members −

Class StaticVar
Public Shared num As Integer
Public Sub count()
num = num + 1
End Sub
Public Shared Function getNum() As Integer
Return num
End Function
Shared Sub Main()
Dim s As StaticVar = New StaticVar()
s.count()
s.count()
s.count()
Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Value of variable num: 3

Inheritance
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class which makes it easier to create
and maintain an application. This also provides an opportunity to reuse the code functionality
and fast implementation time.
When creating a class, instead of writing completely new data members and member functions,
the programmer can designate that the new class should inherit the members of an existing class.
This existing class is called the base class, and the new class is referred to as the derived class.

Base & Derived Classes


A class can be derived from more than one class or interface, which means that it can inherit data
and functions from multiple base classes or interfaces.
The syntax used in VB.Net for creating derived classes is as follows −
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Consider a base class Shape and its derived class Rectangle −

' Base class


Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Total area: 35

Base Class Initialization


The derived class inherits the base class member variables and member methods. Therefore, the
super class object should be created before the subclass is created. The super class or the base
class is implicitly known as MyBase in VB.Net
The following program demonstrates this −

' Base class


Class Rectangle
Protected width As Double
Protected length As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
length = l
width = w
End Sub
Public Function GetArea() As Double
Return (width * length)
End Function
Public Overridable Sub Display()
Console.WriteLine("Length: {0}", length)
Console.WriteLine("Width: {0}", width)
Console.WriteLine("Area: {0}", GetArea())
End Sub
'end class Rectangle
End Class

'Derived class
Class Tabletop : Inherits Rectangle
Private cost As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
MyBase.New(l, w)
End Sub
Public Function GetCost() As Double
Dim cost As Double
cost = GetArea() * 70
Return cost
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
'end class Tabletop
End Class
Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
VB.Net supports multiple inheritance.

VB.Net - Basic 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 happens 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.
For example, the MessageBox control has a method named Show, which is called in the code
snippet below −
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
MessageBox.Show("Hello, World")
End Sub
End Class
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 −
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'event handler code goes here
End Sub
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 −

Sr.No. Widget & Description

1
Forms
The container for all the controls that make up the user interface.

2
TextBox
It represents a Windows text box control.

3
Label
It represents a standard Windows label.

4
Button
It represents a Windows button control.

5
ListBox
It represents a Windows control to display a list of items.

6
ComboBox
It represents a Windows combo box control.

7
RadioButton
It enables the user to select a single option from a group of choices when paired with
other RadioButton controls.

8
CheckBox
It represents a Windows CheckBox.

9
PictureBox
It represents a Windows picture box control for displaying an image.

10
ProgressBar
It represents a Windows progress bar control.

11
ScrollBar
It Implements the basic functionality of a scroll bar control.

12
DateTimePicker
It represents a Windows control that allows the user to select a date and a time and to
display the date and time with a specified format.
13
TreeView
It displays a hierarchical collection of labeled items, each represented by a TreeNode.

14
ListView
It represents a Windows list view control, which displays a collection of items that can
be displayed using one of four different views.

VB.Net - Event Handling

Events are basically a user action like key press, clicks, mouse movements, etc., or some
occurrence like system generated notifications. Applications need to respond to events when they
occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all are
examples of events. An event is an action that calls a function or may cause another event. Event
handlers are functions that tell how to respond to an event.
VB.Net is an event-driven language. There are mainly two types of events −
 Mouse events
 Keyboard events

Handling Mouse Events


Mouse events occur with mouse movements in forms and controls. Following are the various
mouse events related with a Control class −
 MouseDown − it occurs when a mouse button is pressed
 MouseEnter − it occurs when the mouse pointer enters the control
 MouseHover − it occurs when the mouse pointer hovers over the control
 MouseLeave − it occurs when the mouse pointer leaves the control
 MouseMove − it occurs when the mouse pointer moves over the control
 MouseUp − it occurs when the mouse pointer is over the control and the mouse button is
released
 MouseWheel − it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of type MouseEventArgs. The
MouseEventArgs object is used for handling mouse events. It has the following properties −
 Buttons − indicates the mouse button pressed
 Clicks − indicates the number of clicks
 Delta − indicates the number of detents the mouse wheel rotated
 X − indicates the x-coordinate of mouse click
 Y − indicates the y-coordinate of mouse click

Example
Following is an example, which shows how to handle mouse events. Take the following steps −
 Add three labels, three text boxes and a button control in the form.
 Change the text properties of the labels to - Customer ID, Name and Address,
respectively.
 Change the name properties of the text boxes to txtID, txtName and txtAddress,
respectively.
 Change the text property of the button to 'Submit'.
 Add the following code in the code editor window −
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub

Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_


Handles txtID.MouseEnter
'code for handling mouse enter on ID textbox
txtID.BackColor = Color.CornflowerBlue
txtID.ForeColor = Color.White
End Sub

Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _


Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox
txtID.BackColor = Color.White
txtID.ForeColor = Color.Blue
End Sub

Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _


Handles txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub

Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _


Handles txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White
txtName.ForeColor = Color.Blue
End Sub
Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _
Handles txtAddress.MouseEnter
'code for handling mouse enter on Address textbox
txtAddress.BackColor = Color.CornflowerBlue
txtAddress.ForeColor = Color.White
End Sub

Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _


Handles txtAddress.MouseLeave
'code for handling mouse leave on Address textbox
txtAddress.BackColor = Color.White
txtAddress.ForeColor = Color.Blue
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
MsgBox("Thank you " & txtName.Text & ", for your kind cooperation")
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −

Try to enter text in the text boxes and check the mouse events −
Handling Keyboard Events
Following are the various keyboard events related with a Control class −
 KeyDown − occurs when a key is pressed down and the control has focus
 KeyPress − occurs when a key is pressed and the control has focus
 KeyUp − occurs when a key is released while the control has focus
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs.
This object has the following properties −
 Alt − it indicates whether the ALT key is pressed
 Control − it indicates whether the CTRL key is pressed
 Handled − it indicates whether the event is handled
 KeyCode − stores the keyboard code for the event
 KeyData − stores the keyboard data for the event
 KeyValue − stores the keyboard value for the event
 Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
 Shift − it indicates if the Shift key is pressed
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs.
This object has the following properties −
 Handled − indicates if the KeyPress event is handled
 KeyChar − stores the character corresponding to the key pressed

Example
Let us continue with the previous example to show how to handle keyboard events. The code
will verify that the user enters some numbers for his customer ID and age.
 Add a label with text Property as 'Age' and add a corresponding text box named txtAge.
 Add the following codes for handling the KeyUP events of the text box txtID.
Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtID.KeyUp

If (Not Char.IsNumber(ChrW(e.KeyCode))) Then


MessageBox.Show("Enter numbers for your Customer ID")
txtID.Text = " "
End If
End Sub
 Add the following codes for handling the KeyUP events of the text box txtID.
Private Sub txtAge_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtAge.KeyUp

If (Not Char.IsNumber(ChrW(e.keyCode))) Then


MessageBox.Show("Enter numbers for age")
txtAge.Text = " "
End If
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −

If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning
message box and clears the respective text −
VB.Net - Regular Expressions

A regular expression is a pattern that could be matched against an input text. The .Net
framework provides a regular expression engine that allows such matching. A pattern consists of
one or more character literals, operators, or constructs.

Constructs for Defining Regular Expressions


There are various categories of characters, operators, and constructs that lets you to define
regular expressions. Click the following links to find these constructs.
 Character escapes
 Character classes
 Anchors
 Grouping constructs
 Quantifiers
 Backreference constructs
 Alternation constructs
 Substitutions
 Miscellaneous constructs

The Regex Class


The Regex class is used for representing a regular expression.
The Regex class has the following commonly used methods −

Sr.No. Methods & Description

1
Public Function IsMatch (input As String) As Boolean
Indicates whether the regular expression specified in the Regex constructor finds a
match in a specified input string.

2
Public Function IsMatch (input As String, startat As Integer ) As Boolean
Indicates whether the regular expression specified in the Regex constructor finds a
match in the specified input string, beginning at the specified starting position in the
string.

3
Public Shared Function IsMatch (input As String, pattern As String ) As Boolean
Indicates whether the specified regular expression finds a match in the specified input
string.

4
Public Function Matches (input As String) As MatchCollection
Searches the specified input string for all occurrences of a regular expression.

5
Public Function Replace (input As String, replacement As String) As String
In a specified input string, replaces all strings that match a regular expression pattern
with a specified replacement string.

6
Public Function Split (input As String) As String()
Splits an input string into an array of substrings at the positions defined by a regular
expression pattern specified in the Regex constructor.

For the complete list of methods and properties, please consult Microsoft documentation.

Example 1
The following example matches words that start with 'S' −
Imports System.Text.RegularExpressions
Module regexProg
Sub showMatch(ByVal text As String, ByVal expr As String)
Console.WriteLine("The Expression: " + expr)
Dim mc As MatchCollection = Regex.Matches(text, expr)
Dim m As Match

For Each m In mc
Console.WriteLine(m)
Next m
End Sub

Sub Main()
Dim str As String = "A Thousand Splendid Suns"
Console.WriteLine("Matching words that start with 'S': ")
showMatch(str, "\bS\S*")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Matching words that start with 'S':
The Expression: \bS\S*
Splendid
Suns

Example 2
The following example matches words that start with 'm' and ends with 'e' −

Imports System.Text.RegularExpressions
Module regexProg
Sub showMatch(ByVal text As String, ByVal expr As String)
Console.WriteLine("The Expression: " + expr)
Dim mc As MatchCollection = Regex.Matches(text, expr)
Dim m As Match

For Each m In mc
Console.WriteLine(m)
Next m
End Sub

Sub Main()
Dim str As String = "make a maze and manage to measure it"
Console.WriteLine("Matching words that start with 'm' and ends with 'e': ")
showMatch(str, "\bm\S*e\b")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Matching words start with 'm' and ends with 'e':
The Expression: \bm\S*e\b
make
maze
manage
measure

Example 3
This example replaces extra white space −

Imports System.Text.RegularExpressions
Module regexProg
Sub Main()
Dim input As String = "Hello World "
Dim pattern As String = "\\s+"
Dim replacement As String = " "
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement)

Console.WriteLine("Original String: {0}", input)


Console.WriteLine("Replacement String: {0}", result)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Original String: Hello World
Replacement String: Hello World
VB.Net - Web Programming

A dynamic web application consists of either or both of the following two types of programs −
 Server-side scripting − these are programs executed on a web server, written using
server-side scripting languages like ASP (Active Server Pages) or JSP (Java Server
Pages).
 Client-side scripting − these are programs executed on the browser, written using
scripting languages like JavaScript, VBScript, etc.
ASP.Net is the .Net version of ASP, introduced by Microsoft, for creating dynamic web pages by
using server-side scripts. ASP.Net applications are compiled codes written using the extensible
and reusable components or objects present in .Net framework. These codes can use the entire
hierarchy of classes in .Net framework.
The ASP.Net application codes could be written in either of the following languages −
 Visual Basic .Net
 C#
 Jscript
 J#
In this chapter, we will give a very brief introduction to writing ASP.Net applications using
VB.Net. For detailed discussion, please consult the ASP.Net Tutorial.

ASP.Net Built-in Objects


ASP.Net has some built-in objects that run on a web server. These objects have methods,
properties and collections that are used in application development.
The following table lists the ASP.Net built-in objects with a brief description –

Sr.No. Object & Description


1
Application
Describes the methods, properties, and collections of the object that stores information
related to the entire Web application, including variables and objects that exist for the
lifetime of the application.
You use this object to store and retrieve information to be shared among all users of an
application. For example, you can use an Application object to create an e-commerce
page.

2
Request
Describes the methods, properties, and collections of the object that stores information
related to the HTTP request. This includes forms, cookies, server variables, and
certificate data.
You use this object to access the information sent in a request from a browser to the
server. For example, you can use a Request object to access information entered by a
user in an HTML form.

3
Response
Describes the methods, properties, and collections of the object that stores information
related to the server's response. This includes displaying content, manipulating
headers, setting locales, and redirecting requests.
You use this object to send information to the browser. For example, you use a
Response object to send output from your scripts to a browser.

4
Server
Describes the methods and properties of the object that provides methods for various
server tasks. With these methods you can execute code, get error conditions, encode
text strings, create objects for use by the Web page, and map physical paths.
You use this object to access various utility functions on the server. For example, you
may use the Server object to set a time out for a script.

5
Session
Describes the methods, properties, and collections of the object that stores information
related to the user's session, including variables and objects that exist for the lifetime of
the session.
You use this object to store and retrieve information about particular user sessions. For
example, you can use Session object to keep information about the user and his
preference and keep track of pending operations.

ASP.Net Programming Model


ASP.Net provides two types of programming models −
 Web Forms − this enables you to create the user interface and the application logic that
would be applied to various components of the user interface.
 WCF Services − this enables you to remote access some server-side functionalities.
For this chapter, you need to use Visual Studio Web Developer, which is free. The IDE is almost
same as you have already used for creating the Windows Applications.

Web Forms
Web forms consists of −
 User interface
 Application logic
User interface consists of static HTML or XML elements and ASP.Net server controls. When
you create a web application, HTML or XML elements and server controls are stored in a file
with .aspx extension. This file is also called the page file.
The application logic consists of code applied to the user interface elements in the page. You
write this code in any of .Net language like, VB.Net, or C#. The following figure shows a Web
Form in Design view −
Example
Let us create a new web site with a web form, which will show the current date and time, when a
user clicks a button. Take the following steps −
 Select File → New → Web Site. The New Web Site Dialog Box appears.

 Select the ASP.Net Empty Web Site templates. Type a name for the web site and select a
location for saving the files.
 You need to add a Default page to the site. Right click the web site name in the Solution
Explorer and select Add New Item option from the context menu. The Add New Item
dialog box is displayed −
 Select Web Form option and provide a name for the default page. We have kept it as
Default.aspx. Click the Add button.
 The Default page is shown in Source view

 Set the title for the Default web page by adding a value to the <Title> tag of the page, in
the Source view −
 To add controls on the web page, go to the design view. Add three labels, a text box and a
button on the form.
 Double-click the button and add the following code to the Click event of the button −
Protected Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Label2.Visible = True
Label2.Text = "Welcome to Tutorials Point: " + TextBox1.Text
Label3.Text = "You visited us at: " + DateTime.Now.ToString()
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, the following page opens in the browser −

Enter your name and click on the Submit button −


Web Services
A web service is a web application, which is basically a class consisting of methods that could be
used by other applications. It also follows a code-behind architecture like the ASP.Net web
pages, although it does not have an user interface.
The previous versions of .Net Framework used this concept of ASP.Net Web Service, which had
.asmx file extension. However, from .Net Framework 4.0 onwards, the Windows
Communication Foundation (WCF) technology has evolved as the new successor of Web
Services, .Net Remoting and some other related technologies. It has rather clubbed all these
technologies together. In the next section, we will provide a brief introduction to Windows
Communication Foundation(WCF).
If you are using previous versions of .Net Framework, you can still create traditional web
services. Please consult ASP.Net - Web Services tutorial for detailed description.

Windows Communication Foundation


Windows Communication Foundation or WCF provides an API for creating distributed service-
oriented applications, known as WCF Services.
Like Web services, WCF services also enable communication between applications. However,
unlike web services, the communication here is not limited to HTTP only. WCF can be
configured to be used over HTTP, TCP, IPC, and Message Queues. Another strong point in
favour of WCF is, it provides support for duplex communication, whereas with web services we
could achieve simplex communication only.
From beginners' point of view, writing a WCF service is not altogether so different from writing
a Web Service. To keep the things simple, we will see how to −
 Create a WCF Service
 Create a Service Contract and define the operations
 Implement the contract
 Test the Service
 Utilize the Service

Example
To understand the concept let us create a simplistic service that will provide stock price
information. The clients can query about the name and price of a stock based on the stock
symbol. To keep this example simple, the values are hardcoded in a two-dimensional array. This
service will have two methods −
 GetPrice Method − it will return the price of a stock, based on the symbol provided.
 GetName Method − it will return the name of the stock, based on the symbol provided.
Creating a WCF Service
Take the following steps −
 Open VS Express for Web 2012
 Select New Web Site to open the New Web Site dialog box.
 Select WCF Service template from list of templates −

 Select File System from the Web location drop-down list.


 Provide a name and location for the WCF Service and click OK.
 A new WCF Service is created.
Creating a Service Contract and Defining the Operations
A service contract defines the operation that a service performs. In the WCF Service application,
you will find two files automatically created in the App_Code folder in the Solution Explorer
 IService.vb − this will have the service contract; in simpler words, it will have the
interface for the service, with the definitions of methods the service will provide, which
you will implement in your service.
 Service.vb − this will implement the service contract.
 Replace the code of the IService.vb file with the given code −
Public Interface IService
<OperationContract()>
Function GetPrice(ByVal symbol As String) As Double

<OperationContract()>
Function GetName(ByVal symbol As String) As String
End Interface
Implementing the Contract
In the Service.vb file, you will find a class named Service which will implement the Service
Contract defined in the IService interface.
Replace the code of IService.vb with the following code −
' NOTE: You can use the "Rename" command on the context menu to change the class name
"Service" in code, svc and config file together.
Public Class Service
Implements IService
Public Sub New()
End Sub
Dim stocks As String(,) =
{
{"RELIND", "Reliance Industries", "1060.15"},
{"ICICI", "ICICI Bank", "911.55"},
{"JSW", "JSW Steel", "1201.25"},
{"WIPRO", "Wipro Limited", "1194.65"},
{"SATYAM", "Satyam Computers", "91.10"}
}

Public Function GetPrice(ByVal symbol As String) As Double _


Implements IService.GetPrice

Dim i As Integer
'it takes the symbol as parameter and returns price
For i = 0 To i = stocks.GetLength(0) - 1

If (String.Compare(symbol, stocks(i, 0)) = 0) Then


Return Convert.ToDouble(stocks(i, 2))
End If
Next i
Return 0
End Function

Public Function GetName(ByVal symbol As String) As String _


Implements IService.GetName

' It takes the symbol as parameter and


' returns name of the stock
Dim i As Integer
For i = 0 To i = stocks.GetLength(0) - 1

If (String.Compare(symbol, stocks(i, 0)) = 0) Then


Return stocks(i, 1)
End If
Next i
Return "Stock Not Found"
End Function
End Class
Testing the Service
To run the WCF Service, so created, select the Debug → Start Debugging option from the menu
bar. The output would be −
For testing the service operations, double click the name of the operation from the tree on the left
pane. A new tab will appear on the right pane.
Enter the value of parameters in the Request area of the right pane and click the 'Invoke' button.
The following diagram displays the result of testing the GetPrice operation −
The following diagram displays the result of testing the GetName operation −
Utilizing the Service
Let us add a default page, a ASP.NET web form in the same solution from which we will be
using the WCF Service we have just created.
Take the following steps −
 Right click on the solution name in the Solution Explorer and add a new web form to the
solution. It will be named Default.aspx.
 Add two labels, a text box and a button on the form.

 We need to add a service reference to the WCF service we just created. Right click the
website in the Solution Explorer and select Add Service Reference option. This opens the
Add Service Reference Dialog box.
 Enter the URL(location) of the Service in the Address text box and click the Go button. It
creates a service reference with the default name ServiceReference1. Click the OK
button.
Adding the reference does two jobs for your project −
 Creates the Address and Binding for the service in the web.config file.
 Creates a proxy class to access the service.
 Double click the Get Price button in the form, to enter the following code snippet on its
Click event −
Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
Dim ser As ServiceReference1.ServiceClient = _
New ServiceReference1.ServiceClient
Label2.Text = ser.GetPrice(TextBox1.Text).ToString()
End Sub
End Class
 When the above code is executed and run using Start button available at the Microsoft
Visual Studio tool bar, the following page opens in the browser −
 Enter a symbol and click the Get Price button to get the hard-coded price −

You might also like