Unit.3 Web Programming With V.B
Unit.3 Web Programming With V.B
Unit.3 Web Programming With V.B
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.
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.
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.
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.
Double 8 bytes
-1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative
values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive
values
Single 4 bytes
-3.4028235E+38 through -1.401298E-45 for
negative values;
1.401298E-45 through 3.4028235E+38 for
positive values
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 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
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.
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
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
VB.Net - Statements
A statement is a complete instruction in Visual Basic programs. It may contain keywords, operators,
variables, literal values, constants and expressions.
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
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
/ 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
= 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
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.
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.
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
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
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
= 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
/= 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
Miscellaneous Operators
There are few other important operators supported by VB.Net.
Show Examples
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))
Operator Precedence
Await Highest
Exponentiation (^)
Unary identity and negation (+, -)
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like, TypeOf...Is)
Negation (Not)
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
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.
Nested loops You can use one or more loops inside any another While, For or
Do loop.
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.
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
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
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.
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: ")
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.
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
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result 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
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
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
'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
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
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
'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
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
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub
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.
'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.
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 −
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.
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
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
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 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.
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)
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.
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.
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 −
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 −
<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"}
}
Dim i As Integer
'it takes the symbol as parameter and returns price
For i = 0 To i = stocks.GetLength(0) - 1
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