Tutorial
Tutorial
NET
VB.NET
Audience
This tutorial has been prepared for the beginners to help them understand basic
VB.Net programming. After completing this tutorial, you will find yourself at a
moderate level of expertise in VB.Net programming from where you can take
yourself to next levels.
Prerequisites
VB.Net programming is very much based on BASIC and Visual Basic programming
languages, so if you have basic understanding on these programming languages,
then it will be a fun for you to learn VB.Net programming language.
VB.NET
Table of Contents
About the Tutorial ................................................................................................................................... 1
Audience ................................................................................................................................................. 1
Prerequisites ........................................................................................................................................... 1
Copyright & Disclaimer............................................................................................................................ 1
Table of Contents .................................................................................................................................... 2
1.
OVERVIEW........................................................................................................................... 8
Strong Programming Features VB.Net ..................................................................................................... 8
2.
ENVIRONMENT SETUP....................................................................................................... 10
The .Net Framework ............................................................................................................................. 10
Integrated Development Environment (IDE) For VB.Net ....................................................................... 11
Writing VB.Net Programs on Linux or Mac OS ....................................................................................... 11
3.
PROGRAM STRUCTURE...................................................................................................... 12
VB.Net Hello World Example ................................................................................................................. 12
Compile & Execute VB.Net Program ...................................................................................................... 13
4.
5.
VB.NET
6.
VARIABLES ......................................................................................................................... 25
Variable Declaration in VB.Net .............................................................................................................. 25
Variable Initialization in VB.Net ............................................................................................................ 27
Example ................................................................................................................................................ 27
Accepting Values from User .................................................................................................................. 28
Lvalues and Rvalues .............................................................................................................................. 28
7.
8.
MODIFIERS ........................................................................................................................ 35
List of Available Modifiers in VB.Net ..................................................................................................... 35
9.
STATEMENTS ..................................................................................................................... 40
Declaration Statements ......................................................................................................................... 40
Executable Statements .......................................................................................................................... 44
VB.NET
Example ................................................................................................................................................ 59
Assignment Operators........................................................................................................................... 60
Example ................................................................................................................................................ 61
Miscellaneous Operators ...................................................................................................................... 62
Example ................................................................................................................................................ 63
Operators Precedence in VB.Net ........................................................................................................... 64
Example ................................................................................................................................................ 65
VB.NET
14. STRINGS............................................................................................................................. 98
Creating a String Objec .......................................................................................................................... 98
Properties of the String Class ................................................................................................................ 99
Methods of the String Class ................................................................................................................... 99
Examples ............................................................................................................................................. 105
VB.NET
VB.NET
1. Overview
VB.NET
Object oriented.
Component oriented.
Easy to learn.
Structured language.
Boolean Conditions
Standard Library
8
VB.NET
Assembly Versioning
Properties and Events
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
2. Environment Setup
VB.NET
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.
Windows applications
Web applications
Web services
Windows Forms
ADO.Net
10
VB.NET
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.
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.
11
3. Program Structure
VB.NET
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.
Namespace declaration
A class or module
Variables
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.
12
VB.NET
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.
Sub
Operator
Get
Set
AddHandler
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 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.
VB.NET
Specify a name and location for your project using the Browse button, and
then choose the OK button.
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 the command prompt tool and go to the directory where you saved
the file.
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.
14
4. Basic Syntax
VB.NET
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.
Instant Variables - Each object has its unique set of instant variables. An
object's state is created by the values assigned to these instant variables.
'Public methods
Public Sub AcceptDetails()
15
VB.NET
length = 4.5
width = 3.5
End Sub
End Sub
16
VB.NET
A class may have members that can be accessible from outside class, if so
specified. Data members are called fields and procedure members are called
methods.
Shared methods or static methods can be invoked without creating an object of
the class. Instance methods are invoked through an object of the class:
Shared Sub Main()
Dim r As New Rectangle()
r.Acceptdetails()
r.Display()
Console.ReadLine()
End Sub
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:
VB.Net Keywords
The following table lists the VB.Net reserved keywords:
AddHandler
AddressOf
Alias
And
AndAlso
As
Boolean
ByRef
Byte
ByVal
Call
Case
Catch
CBool
CByte
CChar
CDate
CDec
CDbl
Char
CInt
Class
CLng
CObj
Const
Continue
CSByte
CShort
CSng
CStr
CType
CUInt
CULng
CUShort
Date
17
VB.NET
Decimal
Declare
Default
Delegate
Dim
DirectCast
Do
Double
Each
Else
ElseIf
End
End If
Enum
Erase
Error
Event
Exit
False
Finally
For
Friend
Function
Get
GetType
Global
GoTo
GetXML
Namespace
Handles
If
Implements
Imports
In
Inherits
Integer
Interface
Is
IsNot
Let
Lib
Like
Long
Loop
Me
Mod
Module
MustInherit
MustOverride
MyBase
MyClass
Namespace
Narrowing
New
Next
Not
Nothing
Not
Not
Object
Of
On
Operator
Option
Inheritable
Overridable
Optional
Or
OrElse
Overloads
Overridable
Overrides
ParamArray
Partial
Private
Property
Protected
Public
RaiseEvent
ReadOnly
Resume
Return
SByte
Select
Remove
ReDim
REM
Handler
Set
Shadows
Shared
Short
Single
Static
Step
Stop
String
Structure
Sub
SyncLock
Then
Throw
To
True
Try
TryCast
TypeOf
UInteger
While
Widening
With
WithEvents
WriteOnly
Xor
18
5. Data Types
VB.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.
Storage
Allocation
Value Range
Boolean
Depends on
implementing
platform
True or False
Byte
1 byte
Char
2 bytes
Date
8 bytes
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
Decimal
Double
8 bytes
19
VB.NET
Integer
4 bytes
-2,147,483,648
(signed)
Long
8 bytes
-9,223,372,036,854,775,808
through
9,223,372,036,854,775,807(signed)
Object
4 bytes on 32-bit
platform
8 bytes on 64-bit
platform
through
2,147,483,647
SByte
1 byte
Short
2 bytes
Single
4 bytes
String
Depends on
implementing
platform
0 to approximately
characters
UInteger
4 bytes
ULong
8 bytes
0 through
(unsigned)
UserDefined
Depends on
implementing
platform
UShort
2 bytes
billion
Unicode
18,446,744,073,709,551,615
20
VB.NET
Example
The following example demonstrates use of some of the types:
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()
21
VB.NET
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
CBool(expression)
Converts the expression to Boolean data type.
CByte(expression)
Converts the expression to Byte data type.
CChar(expression)
Converts the expression to Char data type.
CDate(expression)
Converts the expression to Date data type
CDbl(expression)
Converts the expression to Double data type.
CDec(expression)
Converts the expression to Decimal data type.
22
VB.NET
CInt(expression)
Converts the expression to Integer data type.
CLng(expression)
Converts the expression to Long data type.
CObj(expression)
Converts the expression to Object type.
10
CSByte(expression)
Converts the expression to SByte data type.
11
CShort(expression)
Converts the expression to Short data type.
12
CSng(expression)
Converts the expression to Single data type.
13
CStr(expression)
Converts the expression to String data type.
14
CUInt(expression)
Converts the expression to UInt data type.
15
CULng(expression)
Converts the expression to ULng data type.
16
CUShort(expression)
Converts the expression to UShort data type.
23
VB.NET
Example
The following example demonstrates some of these functions:
Module DataTypes
Sub Main()
Dim n As Integer
Dim da As Date
Dim bl As Boolean = True
n = 1234567
da = Today
Console.WriteLine(bl)
Console.WriteLine(CSByte(bl))
Console.WriteLine(CStr(bl))
Console.WriteLine(CStr(da))
Console.WriteLine(CChar(CChar(CStr(n))))
Console.WriteLine(CChar(CStr(da)))
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
True
-1
True
12/4/2012
1
1
24
6. Variables
VB.NET
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
Decimal types
Decimal
Boolean types
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.
VB.NET
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.
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.
Each variable in the variable list has the following syntax and parts:
variablename[ ( [ boundslist ] ) ] [ As [ New ] datatype ] [ =
initializer ]
Where,
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.
Some valid variable declarations along with their definition are shown here:
Dim StudentID As Integer
Dim StudentName As String
Dim Salary As Double
26
VB.NET
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
27
VB.NET
When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30
rvalue : An expression that is an rvalue may appear on the right- but not
left-hand side of an assignment.
28
VB.NET
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
29
VB.NET
The constants refer to fixed values that the program may not alter during its
execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are also enumeration
constants as well.
The constants are treated just like regular variables except that their values
cannot be modified after their definition.
An enumeration is a set of named integer constants.
Declaring Constants
In VB.Net, constants are declared using the Const statement. The Const
statement is used at module, class, structure, procedure, or block level for use in
place of literal values.
The syntax for the Const statement is:
[ < attributelist> ] [ accessmodifier ] [ Shadows ]
Const constantlist
Where,
Where, each constant name has the following syntax and parts:
constantname [ As datatype ] = initializer
VB.NET
For example,
' The following statements declare constants.
Const maxval As Long = 4999
Public Const message As String = "HELLO"
Private Const piValue As Double = 3.1415
Example
The following example demonstrates declaration and use of a constant value:
Module constantsNenum
Sub Main()
Const PI = 3.14149
Dim radius, area As Single
radius = 7
area = PI * radius * radius
Console.WriteLine("Area = " & Str(area))
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Area = 153.933
Description
vbCrLf
vbCr
vbLf
Linefeed character.
31
VB.NET
vbNewLine
Newline character.
vbNullChar
Null character.
vbNullString
vbObjectError
vbTab
Tab character.
vbBack
Backspace character.
Declaring Enumerations
An enumerated type is declared using the Enum statement. The Enum statement
declares an enumeration and defines the values of its members. The Enum
statement can be used at the module, class, structure, procedure, or block level.
The syntax for the Enum statement is as follows:
[ < attributelist > ] [ accessmodifier ]
[ Shadows ]
datatype: specifies the data type of the enumeration and all its members.
32
VB.NET
Each member in the memberlist has the following syntax and parts:
[< attribute list>] member name [ = initializer ]
Where,
For example,
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Example
The following example demonstrates declaration and use of the Enum
variable Colors:
Module constantsNenum
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Sub Main()
33
VB.NET
34
8. Modifiers
VB.NET
The modifiers are keywords added with any programming element to give some
especial emphasis on how the programming element will behave or will be
accessed in the program
For example, the access modifiers: Public, Private, Protected, Friend, Protected
Friend, etc., indicate the access level of a programming element like a variable,
constant, enumeration, or a class.
Modifier
Description
Ansi
Assembly
Async
Auto
ByRef
35
VB.NET
ByVal
Declare Statement
Function Statement
Operator Statement
Property Statement
Sub Statement
Default
Friend
In
10
Iterator
11
Key
36
VB.NET
12
Module
13
MustInherit
MustOverride
15
Narrowing
16
NotInheritable
17
NotOverridable
18
Optional
19
Out
Overloads
Overridable
Overrides
14
20
21
22
37
VB.NET
23
ParamArray
24
Partial
25
Private
26
Protected
27
Public
28
ReadOnly
Shadows
Shared
Static
Unicode
29
30
31
32
38
VB.NET
33
Widening
34
WithEvents
35
WriteOnly
39
VB.NET
9. Statements
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:
S.N
Dim Statement
Declares and allocates storage space for one
or more variables.
Example
Dim number As
Integer
Dim quantity As
Integer = 100
Dim message As
String = "Hello!"
Const Statement
Declares and defines one or more constants.
Const maximum As
Long = 1000
40
VB.NET
Const naturalLogBase
As Object
= CDec(2.7182818284)
Enum Statement
Declares an enumeration and defines the
values of its members.
Enum CoffeeMugSize
Jumbo
ExtraLarge
Large
Medium
Small
End Enum
Class Statement
Declares the name of a class and introduces
the definition of the variables, properties,
events, and procedures that the class
comprises.
Class Box
Public length As
Double
Public breadth As
Double
Public height As
Double
End Class
Structure Statement
Declares the name of a structure and
introduces the definition of the variables,
properties, events, and procedures that the
structure comprises.
Structure Box
Public length As
Double
Public breadth As
Double
Public height As
Double
End Structure
41
VB.NET
Module Statement
Declares the name of a module and
Public Module
myModule
Sub Main()
Interface Statement
Declares the name of an interface and
introduces the definitions of the members
that the interface comprises.
Function Statement
Declares the name, parameters, and code
that define a Function procedure.
Public Interface
MyInterface
Sub
doSomething()
End Interface
Function myFunction
(ByVal n As Integer)
As Double
Return 5.87 * n
End Function
Sub Statement
Declares the name, parameters, and code
Sub mySub(ByVal s As
String)
Return
End Sub
10
Declare Statement
Declares a reference to a procedure
Declare Function
getUserName
Lib "advapi32.dll"
Alias "GetUserNameA"
(
42
VB.NET
ByVal lpBuffer As
String,
ByRef nSize As
Integer) As Integer
11
Operator Statement
Declares the operator symbol, operands, and
code that define an operator procedure on a
class or structure.
Public Shared
Operator +
(ByVal x As obj,
ByVal y As obj) As
obj
Dim r As New
obj
' implemention code
for r = x + y
Return r
End Operator
12
Property Statement
Declares the name of a property, and the
property procedures used to store and
retrieve the value of the property.
ReadOnly Property
quote() As String
Get
Return
quoteString
End Get
End Property
13
Event Statement
Declares a user-defined event.
14
Delegate Statement
Used to declare a delegate.
Public Event
Finished()
Delegate Function
MathOperator(
ByVal x As
Double,
ByVal y As
Double
) As Double
43
VB.NET
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
44
10. Directives
VB.NET
The VB.Net compiler directives give instructions to the compiler to preprocess the
information before actual compilation starts. All these directives begin with #, and
only white-space characters may appear before a directive on a line. These
directives are not statements.
VB.Net compiler does not have a separate preprocessor; however, the directives
are processed as if there was one. In VB.Net, the compiler directives are used to
help in conditional compilation. Unlike C and C++ directives, they are not used to
create macros.
For example,
#Const state = "WEST BENGAL"
45
VB.NET
Example
The following code demonstrates a hypothetical use of the directive:
Module mydirectives
#Const age = True
Sub Main()
#If age Then
Console.WriteLine("You are welcome to the Robotics Club")
#End If
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
You are welcome to the Robotics Club
Example
The following code demonstrates a hypothetical use of the directive:
Module mydirectives
Public Class ExternalSourceTester
Sub TestExternalSource()
46
VB.NET
#ExternalSource("c:\vbprogs\directives.vb", 5)
Console.WriteLine("This is External Code. ")
#End ExternalSource
End Sub
End Class
Sub Main()
Dim t As New ExternalSourceTester()
t.TestExternalSource()
Console.WriteLine("In Main.")
Console.ReadKey()
End Sub
When the above code is compiled and executed, it produces the following result:
This is External Code.
In Main.
VB.NET
For example,
#Const TargetOS = "Linux"
#If TargetOS = "Windows 7" Then
' Windows 7 specific code
#ElseIf TargetOS = "WinXP" Then
' Windows XP specific code
#Else
' Code for other OS
#End if
Example
The following code demonstrates a hypothetical use of the directive:
Module mydirectives
#Const classCode = 8
Sub Main()
#If classCode = 7 Then
Console.WriteLine("Exam Questions for Class VII")
#ElseIf classCode = 8 Then
Console.WriteLine("Exam Questions for Class VIII")
#Else
Console.WriteLine("Exam Questions for Higher Classes")
#End If
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Exam Questions for Class VIII
VB.NET
#Region "identifier_string"
#End Region
For example,
#Region "StatsFunctions"
' Insert code for the Statistical functions here.
#End Region
49
VB.NET
11. Operators
Arithmetic Operators
Comparison Operators
Logical/Bitwise Operators
Assignment Operators
Miscellaneous 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:
Operator
Description
Example
A + B will give 9
A - B will give -5
A * B will give 14
B \ A will give 3
MOD
VB.NET
Example
Try the following example to understand all the arithmetic operators available in
VB.Net:
Module operators
Sub Main()
Dim a As Integer = 21
Dim b As Integer = 10
Dim p As Integer = 2
Dim c As Integer
Dim d As Single
c = a + b
Console.WriteLine("Line 1 - Value of c is {0}", c)
c = a - b
Console.WriteLine("Line 2 - Value of c is {0}", c)
c = a * b
Console.WriteLine("Line 3 - Value of c is {0}", c)
d = a / b
Console.WriteLine("Line 4 - Value of d is {0}", d)
c = a \ b
Console.WriteLine("Line 5 - Value of c is {0}", c)
c = a Mod b
Console.WriteLine("Line 6 - Value of c is {0}", c)
c = b ^ p
Console.WriteLine("Line 7 - Value of c is {0}", c)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of d is 2.1
Line 5 - Value of c is 2
51
VB.NET
Line 6 - Value of c is 1
Line 7 - Value of c is 100
Comparison Operators
Following table shows all the comparison operators supported by VB.Net. Assume
variable A holds 10 and variable B holds 20, then:
Operator
Description
Example
(A = B) is not
true.
<>
(A <> B) is true.
>
(A > B) is not
true.
<
(A < B) is true.
>=
(A >= B) is not
true.
<=
(A <= B) is true.
Try the following example to understand all the relational operators available in
VB.Net:
Module operators
Sub Main()
Dim a As Integer = 21
Dim b As Integer = 10
52
VB.NET
If (a = b) Then
Console.WriteLine("Line 1 - a is equal to b")
Else
Console.WriteLine("Line 1 - a is not equal to b")
End If
If (a < b) Then
Console.WriteLine("Line 2 - a is less than b")
Else
Console.WriteLine("Line 2 - a is not less than b")
End If
If (a > b) Then
Console.WriteLine("Line 3 - a is greater than b")
Else
Console.WriteLine("Line 3 - a is not greater than b")
End If
' Lets change value of a and b
a = 5
b = 20
If (a <= b) Then
Console.WriteLine("Line 4 - a is either less than or equal to
b")
End If
If (b >= a) Then
Console.WriteLine("Line 5 - b is either greater than
or equal
to b")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
53
VB.NET
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.
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:
Operator
And
Description
Example
(A And B) is
False.
54
VB.NET
Or
(A Or B) is True.
Not
Not(A And B) is
True.
Xor
A Xor B is True.
AndAlso
(A AndAlso B) is
False.
OrElse
(A OrElse B) is
True.
IsFalse
IsTrue
Example
Try the following example to understand all the logical/bitwise operators available
in VB.Net:
Module logicalOp
Sub Main()
Dim a As Boolean = True
Dim b As Boolean = True
Dim c As Integer = 5
55
VB.NET
Dim d As Integer = 20
'logical And, Or and Xor Checking
If (a And b) Then
Console.WriteLine("Line 1 - Condition is true")
End If
If (a Or b) Then
Console.WriteLine("Line 2 - Condition is true")
End If
If (a Xor b) Then
Console.WriteLine("Line 3 - Condition is true")
End If
'bitwise And, Or and Xor Checking
If (c And d) Then
Console.WriteLine("Line 4 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 5 - Condition is true")
End If
If (c Or d) Then
Console.WriteLine("Line 6 - Condition is true")
End If
'Only logical operators
If (a AndAlso b) Then
Console.WriteLine("Line 7 - Condition is true")
End If
If (a OrElse b) Then
Console.WriteLine("Line 8 - Condition is true")
End If
a and b
a = False
b = True
If (a And b) Then
Console.WriteLine("Line 9 - Condition is true")
56
VB.NET
Else
Console.WriteLine("Line 9 - Condition is not true")
End If
If (Not (a And b)) Then
Console.WriteLine("Line 10 - Condition is true")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is true
Line 4 - Condition is true
Line 5 - Condition is true
Line 6 - Condition is true
Line 7 - Condition is true
Line 8 - Condition is true
Line 9 - Condition is not true
Line 10 - Condition is true
p&q
p|q
p^q
57
VB.NET
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:
Operator
Description
Example
And
Or
Xor
Not
<<
58
VB.NET
Example
Try the following example to understand all the bitwise operators available in
VB.Net:
Module BitwiseOp
Sub Main()
Dim a As Integer = 60
Dim b As Integer = 13
Dim c As Integer = 0
c = a And b
VB.NET
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Assignment Operators
There are following assignment operators supported by VB.Net:
Operator
Description
Example
C = A + B will assign
value of A + B into C
+=
C += A is equivalent
to C = C + A
-=
C -= A is equivalent
to C = C - A
*=
C *= A is equivalent
to C = C * A
/=
C /= A is equivalent
to C = C / A
\=
C \= A is equivalent
to C = C \A
^=
C^=A is equivalent
to C = C ^ A
60
VB.NET
<<=
C <<= 2 is same as
C = C << 2
>>=
C >>= 2 is same as
C = C >> 2
&=
Example
Try the following example to understand all the assignment operators available in
VB.Net:
Module assignment
Sub Main()
Dim a As Integer = 21
Dim pow As Integer = 2
Dim str1 As String = "Hello! "
Dim str2 As String = "VB Programmers"
Dim c As Integer
c = a
Console.WriteLine("Line 1 - =
Operator Example, _
Value of c = {0}", c)
c += a
Console.WriteLine("Line 2 - +=
Operator Example, _
Value of c = {0}", c)
c -= a
Console.WriteLine("Line 3 - -=
Operator Example, _
Value of c = {0}", c)
c *= a
Console.WriteLine("Line 4 - *=
Operator Example, _
Value of c = {0}", c)
c /= a
Console.WriteLine("Line 5 - /=
Operator Example, _
61
VB.NET
Value of c = {0}", c)
c = 20
c ^= pow
Console.WriteLine("Line 6 - ^=
Operator Example, _
Value of c = {0}", c)
c <<= 2
Console.WriteLine("Line 7 - <<=
Operator Example,_
Value of c = {0}", c)
c >>= 2
Console.WriteLine("Line 8 - >>=
Operator Example,_
Value of c = {0}", c)
str1 &= str2
Console.WriteLine("Line 9 - &=
Operator Example,_
Miscellaneous Operators
There are few other important operators supported by VB.Net.
Operator
Description
Example
62
VB.NET
AddressOf
AddHandler Button1.Click,
AddressOf Button1_Click
Await
GetType
Function
Expression
It is applied to an
operand
in
an
asynchronous method
or lambda expression
to suspend execution
of the method until the
awaited
task
completes.
It returns a Type
object for the specified
type. The Type object
provides
information
about the type such as
its
properties,
methods, and events.
It
declares
the
parameters and code
that define a function
lambda expression.
MsgBox(GetType(Integer).ToString())
If
It uses short-circuit
evaluation
to
conditionally
return
one of two values. The
If operator can be
called
with
three
arguments or with two
arguments.
Dim num = 5
Console.WriteLine(If(num >= 0,
"Positive", "Negative"))
Example
The following example demonstrates some of these operators:
Module assignment
Sub Main()
63
VB.NET
Dim a As Integer = 21
Console.WriteLine(GetType(Integer).ToString())
Console.WriteLine(GetType(Double).ToString())
Console.WriteLine(GetType(String).ToString())
Dim multiplywith5 = Function(num As Integer) num * 5
Console.WriteLine(multiplywith5(5))
Console.WriteLine(If(a >= 0, "Positive", "Negative"))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
System.Int32
System.Double
System.String
25
Positive
Precedence
Await
Highest
Exponentiation (^)
64
VB.NET
Lowest
Example
The following example demonstrates operator precedence in a simple way:
Module assignment
Sub Main()
Dim a As Integer = 20
Dim b As Integer = 10
Dim c As Integer = 15
Dim d As Integer = 5
Dim e As Integer
e = (a + b) * c / d
' ( 30 * 15 ) / 5
Console.WriteLine("Value of (a + b) * c / d is : {0}", e)
e = ((a + b) * c) / d
' (30 * 15 ) / 5
65
VB.NET
Console.WriteLine("Value of ((a + b) * c) / d is
e = (a + b) * (c / d)
: {0}", e)
Console.WriteLine("Value of (a + b) * (c / d) is
e = a + (b * c) / d
'
: {0}", e)
20 + (150/5)
Console.WriteLine("Value of a + (b * c) / d is
: {0}", e)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is
: 90
Value of (a + b) * (c / d) is
: 90
Value of a + (b * c) / d is
: 50
66
VB.NET
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
If...Then...Else statement
Description
67
VB.NET
nested If statements
If...Then Statement
It is the simplest form of control statement, frequently used in decision making
and changing the control flow of the program execution. Syntax for if-then
statement is:
If condition Then
[Statement(s)]
End If
Where, condition is a Boolean or relational condition and Statement(s) is a simple
or compound statement. Example of an If-Then statement is:
If (a <= 20) Then
c= c+1
End If
If the condition evaluates to true, then the block of code inside the If statement
will be executed. If condition evaluates to false, then the first set of code after the
end of the If statement (after the closing End If) will be executed.
68
VB.NET
Flow Diagram
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 10
69
VB.NET
If...Then...Else Statement
An If statement can be followed by an optional Else statement, which executes
when the Boolean expression is false.
Syntax
The syntax of an If...Then... Else statement in VB.Net is as follows:
If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If
If the Boolean expression evaluates to true, then the if block of code will be
executed, otherwise else block of code will be executed.
Flow Diagram
Example
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
70
VB.NET
An If can have zero or one Else's and it must come after an Else If's.
An If can have zero to many Else If's and they must come before the Else.
Once an Else if succeeds, none of the remaining Else If's or Else's will be
tested.
Syntax
The syntax of an if...else if...else statement in VB.Net is as follows:
If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
71
VB.NET
Example
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 100
' check the boolean condition '
If (a = 10) Then
' if condition is true then print the following '
Console.WriteLine("Value of a is 10") '
ElseIf (a = 20) Then
'if else if condition is true '
Console.WriteLine("Value of a is 20") '
ElseIf (a = 30) Then
'if else if condition is true
Console.WriteLine("Value of a is 30")
Else
'if none of the conditions is true
Console.WriteLine("None of the values is matching")
End If
Console.WriteLine("Exact 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:
None of the values is matching
Exact value of a is: 100
72
VB.NET
Nested If Statements
It is always legal in VB.Net to nest If-Then-Else statements, which means you can
use one If or ElseIf statement inside another If ElseIf statement(s).
Syntax
The syntax for a nested If statement is as follows:
If( boolean_expression 1)Then
'Executes when the boolean expression 1 is true
If(boolean_expression 2)Then
'Executes when the boolean expression 2 is true
End If
End If
You can nest ElseIf...Else in the similar way as you have nested If statement.
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
' check the boolean condition
If (a = 100) Then
' if condition is true then check the following
If (b = 200) Then
' if condition is true then print the following
Console.WriteLine("Value of a is 100 and b is 200")
End If
End If
Console.WriteLine("Exact value of a is : {0}", a)
Console.WriteLine("Exact value of b is : {0}", b)
Console.ReadLine()
End Sub
End Module
73
VB.NET
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
Syntax
The syntax for a Select Case statement in VB.Net is as follows:
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Where,
74
VB.NET
Flow Diagram
Example
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
75
VB.NET
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is
{0}", grade)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Well done
Your grade is B
Example
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Select a
Case 100
Console.WriteLine("This is part of outer case ")
Select Case b
Case 200
Console.WriteLine("This is part of inner case ")
End Select
End Select
Console.WriteLine("Exact value of a is : {0}", a)
Console.WriteLine("Exact value of b is : {0}", b)
Console.ReadLine()
End Sub
76
VB.NET
End Module
When the above code is compiled and executed, it produces the following result:
This is part of outer case
This is part of inner case
Exact value of a is : 100
Exact value of b is : 200
77
13. Loops
VB.NET
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
78
VB.NET
For...Next
For Each...Next
Nested loops
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.
The syntax for this loop construct is:
Do { While | Until } condition
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop
-orDo
[ statements ]
[ Continue Do ]
[ statements ]
79
VB.NET
[ Exit Do ]
[ statements ]
Loop { While | Until } condition
Flow Diagram
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
80
VB.NET
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
The program would behave in same way, if you use an Until statement, instead of
While:
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop Until (a = 20)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
81
VB.NET
value of a: 17
value of a: 18
value of a: 19
For...Next Loop
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.
The syntax for this loop construct is:
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
Flow Diagram
82
VB.NET
Example
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
value of a: 10
83
VB.NET
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
If you want to use a step size of 2, for example, you need to display only even
numbers, between 10 and 20:
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20 Step 2
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 12
value of a: 14
value of a: 16
value of a: 18
value of a: 20
Each...Next Loop
It repeats a group of statements for each element in a collection. This loop is used
for accessing and manipulating all elements in an array or a VB.Net collection.
84
VB.NET
The syntax for this loop construct is:
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
Example
Module loops
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
'displaying the values
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
1
3
5
7
9
VB.NET
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While
Here, statement(s) may be a single statement or a block of statements. The
condition may be any expression, and true is logical true. The loop iterates while
the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
Flow Diagram
86
VB.NET
Here, key point of the While loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the
first statement after the while loop will be executed.
Example
Module loops
Sub Main()
Dim a As Integer = 10
' while loop execution '
While a < 20
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
87
VB.NET
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example
Module loops
Public Class Book
Public Property Name As String
Public Property Author As String
Public Property Subject As String
End Class
Sub Main()
Dim aBook As New Book
With aBook
.Name = "VB.Net Programming"
.Author = "Zara Ali"
.Subject = "Information Technology"
End With
88
VB.NET
With aBook
Console.WriteLine(.Name)
Console.WriteLine(.Author)
Console.WriteLine(.Subject)
End With
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
VB.Net Programming
Zara Ali
Information Technology
Nested Loops
VB.Net allows using one loop inside another loop. Following section shows few
examples to illustrate the concept.
Syntax
The syntax for a nested For loop statement in VB.Net is as follows:
For counter1 [ As datatype1 ] = start1 To end1 [ Step step1 ]
For counter2 [ As datatype2 ] = start2 To end2 [ Step step2 ]
...
Next [ counter2 ]
Next [ counter 1]
The syntax for a nested While loop statement in VB.Net is as follows:
While condition1
While condition2
...
End While
End While
VB.NET
Example
The following program uses a nested for loop to find the prime numbers from 2 to
100:
Module loops
Sub Main()
' local variable definition
Dim i, j As Integer
For i = 2 To 100
For j = 2 To i
' if factor found, not prime
If ((i Mod j) = 0) Then
Exit For
End If
Next j
If (j > (i \ j)) Then
Console.WriteLine("{0} is prime", i)
End If
Next i
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
90
VB.NET
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Control Statement
Description
91
VB.NET
Exit statement
Continue statement
GoTo statement
Exit Statement
The Exit statement transfers the control from a procedure or block immediately to
the statement following the procedure call or the block definition. It terminates
the loop, procedure, try block or the select block from where it is called.
If you are using nested loops (i.e., one loop inside another loop), the Exit
statement will stop the execution of the innermost loop and start executing the
next line of code after the block.
Syntax
The syntax for the Exit statement is:
Exit { Do | For | Function | Property | Select | Sub | Try | While }
Flow Diagram
92
VB.NET
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
' while loop execution '
While (a < 20)
Console.WriteLine("value of a: {0}", a)
a = a + 1
If (a > 15) Then
'terminate the loop using exit statement
Exit While
End If
End While
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
93
VB.NET
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Continue Statement
The Continue statement causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating. It works somewhat like the
Exit statement. Instead of forcing termination, it forces the next iteration of the
loop to take place, skipping any code in between.
For the For...Next loop, Continue statement causes the conditional test and
increment portions of the loop to execute. For the While and Do...While loops,
continue statement causes the program control to pass to the conditional tests.
Syntax
The syntax for a Continue statement is as follows:
Continue { Do | For | While }
Flow Diagram
Example
94
VB.NET
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
Do
If (a = 15) Then
' skip the iteration '
a = a + 1
Continue Do
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
GoTo Statement
The GoTo statement transfers control unconditionally to a specified line in a
procedure.
The syntax for the GoTo statement is:
GoTo label
95
VB.NET
Flow Diagram
Example
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
Line1:
Do
If (a = 15) Then
' skip the iteration '
a = a + 1
GoTo Line1
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
96
VB.NET
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
97
14. Strings
VB.NET
In VB.Net, you can use strings as array of characters, however, more common
practice is to use the String keyword to declare a string variable. The string
keyword is an alias for the System.String class.
VB.NET
Chars
Gets the Char object at a specified position in the current String object.
Length
Gets the number of characters in the current String object.
99
VB.NET
S.N
VB.NET
10
11
12
13
14
15
101
VB.NET
16
17
18
19
20
21
22
102
VB.NET
23
24
25
26
27
28
29
103
VB.NET
30
31
32
33
34
35
36
The above list of methods is not exhaustive, please visit MSDN library for the
complete list of methods and String class constructors.
104
VB.NET
Examples
The following example demonstrates some of the methods mentioned above:
Comparing Strings
#include <include.h>
Module strings
Sub Main()
Dim str1, str2 As String
str1 = "This is test"
str2 = "This is text"
If (String.Compare(str1, str2) = 0) Then
Console.WriteLine(str1 + " and " + str2 +
" are equal.")
Else
Console.WriteLine(str1 + " and " + str2 +
" are not equal.")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
This is test and This is text are not equal.
VB.NET
End Module
When the above code is compiled and executed, it produces the following result:
The sequence 'test' was found.
Getting a Substring
Module strings
Sub Main()
Dim str As String
str = "Last night I dreamt of San Pedro"
Console.WriteLine(str)
Dim substr As String = str.Substring(23)
Console.WriteLine(substr)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Last night I dreamt of San Pedro
San Pedro.
Joining Strings
Module strings
Sub Main()
Dim strarray As String() = {"Down the way where the nights are
gay",
"And the sun shines daily on the mountain
top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",
"I made a stop"}
Dim str As String = String.Join(vbCrLf, strarray)
Console.WriteLine(str)
Console.ReadLine()
106
VB.NET
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
107
VB.NET
Most of the softwares you write need implementing some form of date functions
returning current date and time. Dates are so much part of everyday life that it
becomes easy to work with them without thinking. VB.Net also provides powerful
tools for date arithmetic that makes manipulating dates easy.
The Date data type contains date values, time values, or date and time values.
The default value of Date is 0:00:00 (midnight) on January 1, 0001. The
equivalent .NET data type is System.DateTime.
The DateTime structure represents an instant in time, typically expressed as a
date and time of day
'Declaration
<SerializableAttribute> _
Public Structure DateTime _
Implements IComparable, IFormattable, IConvertible, ISerializable,
IComparable(Of DateTime), IEquatable(Of DateTime)
You can also get the current date and time from the DateAndTime class.
The DateAndTime module contains the procedures and properties used in date
and time operations.
'Declaration
<StandardModuleAttribute> _
Public NotInheritable Class DateAndTime
Note:
Both the DateTime structure and the DateAndTime module contain properties
like Now and Today, so often beginners find it confusing. The DateAndTime
class belongs to the Microsoft.VisualBasic namespace and the DateTime
structure
belongs
to
the
System
namespace.
Therefore, using the later would help you in porting your code to another .Net
language like C#. However, the DateAndTime class/module contains all the
legacy date functions available in Visual Basic.
108
VB.NET
Property
Description
Date
Day
DayOfWeek
DayOfYear
Hour
Kind
Millisecond
Minute
Month
10
Now
of
the
date
109
VB.NET
11
Second
12
Ticks
13
TimeOfDay
14
Today
15
UtcNow
16
Year
some
of
the
commonly
used methods of
110
VB.NET
10
11
111
VB.NET
The above list of methods is not exhaustive, please visit Microsoft documentation for
the complete list of methods and properties of the DateTime structure.
VB.NET
Console.WriteLine(date4)
Console.WriteLine(date5)
Console.ReadKey()
End Sub
End Module
When the above code was compiled and executed, it produces the following result:
12/16/2012 12:00:00 PM
12/16/2012 12:00:52 PM
12/12/2012 10:22:50 PM
12/12/2012 12:00:00 PM
Current Time
Module dateNtime
Sub Main()
Console.Write("Current Time: ")
Console.WriteLine(Now.ToLongTimeString)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Current Time: 11 :05 :32 AM
Current Date
Module dateNtime
Sub Main()
Console.WriteLine("Current Date: ")
Dim dt As Date = Today
Console.WriteLine("Today is: {0}", dt)
113
VB.NET
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Today is: 12/11/2012 12:00:00 AM
Formatting Date
A Date literal should be enclosed within hash signs (# #), and specified in the
format M/d/yyyy, for example #12/16/2012#. Otherwise, your code may change
depending on the locale in which your application is running.
For example, you specified Date literal of #2/6/2012# for the date February 6,
2012. It is alright for the locale that uses mm/dd/yyyy format. However, in a locale
that uses dd/mm/yyyy format, your literal would compile to June 2, 2012. If a
locale uses another format say, yyyy/mm/dd, the literal would be invalid and
cause a compiler error.
To convert a Date literal to the format of your locale or to a custom format, use
the Format function of String class, specifying either a predefined or user-defined
date format.
The following example demonstrates this.
Module dateNtime
Sub Main()
Console.WriteLine("India Wins Freedom: ")
Dim independenceDay As New Date(1947, 8, 15, 0, 0, 0)
' Use format specifiers to control the date display.
Console.WriteLine(" Format 'd:' " & independenceDay.ToString("d"))
Console.WriteLine(" Format 'D:' " & independenceDay.ToString("D"))
Console.WriteLine(" Format 't:' " & independenceDay.ToString("t"))
Console.WriteLine(" Format 'T:' " & independenceDay.ToString("T"))
Console.WriteLine(" Format 'f:' " & independenceDay.ToString("f"))
Console.WriteLine(" Format 'F:' " & independenceDay.ToString("F"))
Console.WriteLine(" Format 'g:' " & independenceDay.ToString("g"))
Console.WriteLine(" Format 'G:' " & independenceDay.ToString("G"))
Console.WriteLine(" Format 'M:' " & independenceDay.ToString("M"))
Console.WriteLine(" Format 'R:' " & independenceDay.ToString("R"))
114
VB.NET
Description
General Date, or G
Short Date, or d
VB.NET
Short Time or t
M, m
R, r
to
the
116
VB.NET
Y, y
For other formats like user-defined formats, please consult Microsoft Documentation.
some
of
the
commonly
used properties of
Property
Description
Date
Now
TimeOfDay
Timer
TimeString
Today
some
of
the
commonly
used methods of
117
VB.NET
DateTime,
Date2
As
DateTime,
DayOfWeek
As
As
DateTime,
FirstDayOfWeekValue
As
118
VB.NET
Public
Shared
Function
MonthName
(Month
As
Integer,
11
12
13
As
Boolean,
FirstDayOfWeekValue
As
FirstDayOfWeek) As String
Returns a String value containing the name of the specified weekday.
14
The above list is not exhaustive. For complete list of properties and methods of
the DateAndTime class, please consult Microsoft Documentation.
The following program demonstrates some of these and methods:
119
VB.NET
Module Module1
Sub Main()
Dim birthday As Date
Dim bday As Integer
Dim month As Integer
Dim monthname As String
' Assign a date using standard short format.
birthday = #7/27/1998#
bday = Microsoft.VisualBasic.DateAndTime.Day(birthday)
month = Microsoft.VisualBasic.DateAndTime.Month(birthday)
monthname = Microsoft.VisualBasic.DateAndTime.MonthName(month)
Console.WriteLine(birthday)
Console.WriteLine(bday)
Console.WriteLine(month)
Console.WriteLine(monthname)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
7/27/1998 12:00:00 AM
27
7
July
120
16. Arrays
VB.NET
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
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
121
VB.NET
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,
VB.NET
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
75
90
80
76
92
99
79
75
10
0
123
VB.NET
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
124
VB.NET
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
125
VB.NET
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
IsFixedSize
Gets a value indicating whether the Array has a fixed size.
IsReadOnly
Gets a value indicating whether the Array is read-only.
Length
Gets a 32-bit integer that represents the total number of elements in all
the dimensions of the Array.
LongLength
Gets a 64-bit integer that represents the total number of elements in all
the dimensions of the Array.
Rank
Gets the rank (number of dimensions) of the Array.
126
VB.NET
VB.NET
10
11
12
13
14
For a complete list of Array class properties and methods, please refer the
Microsoft documentation.
128
VB.NET
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
129
VB.NET
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
130
17. Collections
VB.NET
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.
ArrayList
Hashtable
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
131
VB.NET
Stack
Queue
BitArray
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.
ArrayList
It represents an 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, adding,
searching and sorting items in the list.
lists
some
of
the
commonly
used properties of
132
VB.NET
Property
Description
Capacity
Count
IsFixedSize
IsReadOnly
Item
lists
some
of
the
commonly
used methods of
133
VB.NET
10
11
12
13
VB.NET
14
15
Example
The following example demonstrates the concept:
Sub Main()
Dim al As ArrayList = New ArrayList()
Dim i As Integer
Console.WriteLine("Adding some numbers:")
al.Add(45)
al.Add(78)
al.Add(33)
al.Add(56)
al.Add(12)
al.Add(23)
al.Add(9)
Console.WriteLine("Capacity: {0} ", al.Capacity)
Console.WriteLine("Count: {0}", al.Count)
Console.Write("Content: ")
For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.Write("Sorted Content: ")
al.Sort()
For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
135
VB.NET
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Adding some numbers:
Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78
Hashtable
The Hashtable class represents a collection of key-and-value pairs that are
organized based on the hash code of the key. It uses the key to access the
elements in the collection.
A hashtable is used when you need to access elements by using key, and you can
identify a useful key value. Each item in the hashtable has a key/value pair. The
key is used to access the items in the collection.
lists
some
of
the
commonly
used properties of
Description
Count
IsFixedSize
IsReadOnly
Item
Keys
Values
136
VB.NET
The following table
the Hashtable class:
S.N
lists
some
of
the
commonly
used methods of
Example
The following example demonstrates the concept:
Module collections
Sub Main()
Dim ht As Hashtable = New Hashtable()
Dim k As String
ht.Add("001", "Zara Ali")
ht.Add("002", "Abida Rehman")
ht.Add("003", "Joe Holzner")
ht.Add("004", "Mausam Benazir Nur")
ht.Add("005", "M. Amlan")
ht.Add("006", "M. Arif")
ht.Add("007", "Ritesh Saikia")
If (ht.ContainsValue("Nuha Ali")) Then
Console.WriteLine("This student name is already in the list")
137
VB.NET
Else
ht.Add("008", "Nuha Ali")
End If
' Get a collection of the keys.
Dim key As ICollection = ht.Keys
For Each k In key
Console.WriteLine(" {0} : {1}", k, ht(k))
Next k
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
006: M. Arif
007: Ritesh Saikia
008: Nuha Ali
003: Joe Holzner
002: Abida Rehman
004: Mausam Banazir Nur
001: Zara Ali
005: M. Amlan
SortedList
The SortedList class represents a collection of key-and-value pairs that are sorted
by the keys and are accessible by key and by index.
A sorted list is a combination of an array and a hashtable. 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.
lists
some
of
the
commonly
used properties of
138
VB.NET
Property
Description
Capacity
Count
IsFixedSize
IsReadOnly
Item
Gets and sets the value associated with a specific key in the
SortedList.
Keys
Values
lists
some
of
the
commonly
used methods of
139
VB.NET
10
11
12
13
140
VB.NET
Example
The following example demonstrates the concept:
Module collections
Sub Main()
Dim sl As SortedList = New SortedList()
sl.Add("001", "Zara Ali")
sl.Add("002", "Abida Rehman")
sl.Add("003", "Joe Holzner")
sl.Add("004", "Mausam Benazir Nur")
sl.Add("005", "M. Amlan")
sl.Add("006", "M. Arif")
sl.Add("007", "Ritesh Saikia")
If (sl.ContainsValue("Nuha Ali")) Then
Console.WriteLine("This student name is already in the list")
Else
sl.Add("008", "Nuha Ali")
End If
' Get a collection of the keys.
Dim key As ICollection = sl.Keys
Dim k As String
For Each k In key
Console.WriteLine(" {0} : {1}", k, sl(k))
Next k
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
001: Zara Ali
002: Abida Rehman
003: Joe Holzner
141
VB.NET
Stack
It represents a last-in, first-out collection of objects. 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.
lists
some
of
the
commonly
used properties of
Property
Description
Count
The following table lists some of the commonly used methods of the Stack class:
S.N
1
142
VB.NET
Example
The following example demonstrates use of Stack:
Module collections
Sub Main()
Dim st As Stack = New Stack()
st.Push("A")
st.Push("M")
st.Push("G")
st.Push("W")
Console.WriteLine("Current stack: ")
Dim c As Char
For Each c In st
Console.Write(c + " ")
Next c
Console.WriteLine()
st.Push("V")
st.Push("H")
Console.WriteLine("The next poppable value in stack: {0}",
st.Peek())
Console.WriteLine("Current stack: ")
For Each c In st
Console.Write(c + " ")
Next c
Console.WriteLine()
Console.WriteLine("Removing values ")
st.Pop()
st.Pop()
143
VB.NET
st.Pop()
Console.WriteLine("Current stack: ")
For Each c In st
Console.Write(c + " ")
Next c
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Current stack:
W G M A
The next poppable value in stack: H
Current stack:
H V W G M A
Removing values
Current stack:
G M A
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
lists
some
of
the
commonly
used properties of
Property
Description
Count
The following table lists some of the commonly used methods of the Queue class:
S.N
VB.NET
Example
The following example demonstrates use of Queue:
Module collections
Sub Main()
Dim q As Queue = New Queue()
q.Enqueue("A")
q.Enqueue("M")
q.Enqueue("G")
q.Enqueue("W")
Console.WriteLine("Current queue: ")
Dim c As Char
For Each c In q
Console.Write(c + " ")
Next c
Console.WriteLine()
145
VB.NET
q.Enqueue("V")
q.Enqueue("H")
Console.WriteLine("Current queue: ")
For Each c In q
Console.Write(c + " ")
Next c
Console.WriteLine()
Console.WriteLine("Removing some values ")
Dim ch As Char
ch = q.Dequeue()
Console.WriteLine("The removed value: {0}", ch)
ch = q.Dequeue()
Console.WriteLine("The removed value: {0}", ch)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Current queue:
A M G W
Current queue:
A M G W V H
Removing some values
The removed value: A
The removed value: M
BitArray
The BitArray class manages a compact array of bit values, which are represented
as Booleans, where true indicates that the bit is on (1) and false indicates the bit
is off (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.
146
VB.NET
lists
some
of
the
commonly
used properties of
Property
Description
Count
IsReadOnly
Item
Length
lists
some
of
the
commonly
used methods of
147
VB.NET
Example
The following example demonstrates the use of BitArray class:
Module collections
Sub Main()
'creating two
VB.NET
'content of ba2
Console.WriteLine("Bit array ba2: 13")
For i = 0 To ba2.Count
Console.Write("{0 } ", ba2(i))
Next i
Console.WriteLine()
Dim ba3 As BitArray = New BitArray(8)
ba3 = ba1.And(ba2)
'content of ba3
Console.WriteLine("Bit array ba3 after AND operation: 12")
For i = 0 To ba3.Count
Console.Write("{0 } ", ba3(i))
Next i
Console.WriteLine()
ba3 = ba1.Or(ba2)
'content of ba3
Console.WriteLine("Bit array ba3 after OR operation: 61")
For i = 0 To ba3.Count
Console.Write("{0 } ", ba3(i))
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Bit array ba1: 60
False False True True True True False False
Bit array ba2: 13
True False True True False False False False
Bit array ba3 after AND operation: 12
False False True True False False False False
Bit array ba3 after OR operation: 61
True False True True False False False False
149
VB.NET
150
18. Functions
VB.NET
Functions
Defining a Function
The Function statement is used to declare the name, parameter and the body of
a function. The syntax for the Function statement is:
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Where,
Modifiers: specify the access level of the function; possible values are:
Public, Private, Protected, Friend, Protected Friend and information
regarding overloading, overriding, sharing, and shadowing.
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
151
VB.NET
result = num1
Else
result = num2
End If
FindMax = result
End Function
VB.NET
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:
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
153
VB.NET
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:
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
VB.NET
155
VB.NET
Modifiers: specify the access level of the procedure; possible values are:
Public, Private, Protected, Friend, Protected Friend and information
regarding overloading, overriding, sharing, and shadowing.
Example
The following example demonstrates a Sub procedure CalculatePay that takes two
parameters hours and wages and displays the total pay of an employee:
Module mysub
Sub CalculatePay(ByVal hours As Double, ByVal wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
156
VB.NET
VB.NET
VB.NET
159
VB.NET
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,
accessmodifier defines the access levels of the class, it has values as Public, Protected, Friend, Protected Friend and Private. 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.
VB.NET
The following example demonstrates a Box class, with three data members,
length, breadth, and height:
Module mybox
Class Box
Public length As Double
End Class
Sub Main()
Dim Box1 As Box = New Box()
VB.NET
VB.NET
'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
'constructor
163
VB.NET
'parameterised constructor
VB.NET
'parameterised constructor
' destructor
VB.NET
VB.NET
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.
VB.NET
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:
168
VB.NET
Total area: 35
VB.NET
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.
170
VB.NET
Try: A Try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more Catch blocks.
Syntax
Assuming a block will raise an exception, a method catches an exception using a
combination of the Try and Catch keywords. A Try/Catch block is placed around
the code that might generate an exception. Code within a Try/Catch block is
referred to as protected code, and the syntax for using Try/Catch looks like the
following:
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
171
VB.NET
End Try
You can list down multiple catch statements to catch different type of exceptions
in case your try block raises more than one exception in different situations.
Description
System.IO.IOException
System.IndexOutOfRangeException
System.ArrayTypeMismatchException
System.NullReferenceException
System.DivideByZeroException
System.InvalidCastException
System.OutOfMemoryException
VB.NET
System.StackOverflowException
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in the
form of try and catch blocks. Using these blocks the core program statements are
separated from the error-handling statements.
These error handling blocks are implemented using the Try, Catch and Finally
keywords. Following is an example of throwing an exception when dividing by zero
condition occurs:
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
Exception caught: System.DivideByZeroException: Attempted to divide by
zero.
at ...
Result: 0
173
VB.NET
174
VB.NET
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class. You can use a throw statement in the catch block to throw
the present object as:
Throw [ expression ]
The following program demonstrates this:
Module exceptionProg
Sub Main()
Try
Throw New ApplicationException("A custom exception _
is being thrown here...")
Catch e As Exception
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
A custom exception is being thrown here...
Now inside the Finally Block
175
VB.NET
A file is a collection of data stored in a disk with a specific name and a directory
path. When a file is opened for reading or writing, it becomes a stream.
The stream is basically the sequence of bytes passing through the communication
path. There are two main streams: the input stream and the output stream.
The input stream is used for reading data from file (read operation) and
the output stream is used for writing into the file (write operation).
Description
BinaryReader
BinaryWriter
BufferedStream
Directory
DirectoryInfo
DriveInfo
File
FileInfo
176
VB.NET
FileStream
MemoryStream
Path
StreamReader
StreamWriter
StringReader
StringWriter
creating
FileStream
object F for
reading
file
FileMode
Description
defines
various
methods
for
177
VB.NET
FileAccess
FileShare
writing
Example
The following program demonstrates use of the FileStream class:
Imports System.IO
Module fileProg
178
VB.NET
Sub Main()
Dim f1 As FileStream = New FileStream("test.dat", _
FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim i As Integer
For i = 0 To 20
f1.WriteByte(CByte(i))
Next i
f1.Position = 0
For i = 0 To 20
Console.Write("{0} ", f1.ReadByte())
Next i
f1.Close()
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1
VB.NET
Example
The following example demonstrates reading a text file named Jamaica.txt. The
file reads:
Down the way where the nights are gay
And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop
Imports System.IO
180
VB.NET
Module fileProg
Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As StreamReader = New StreamReader("e:/jamaica.txt")
Dim line As String
' Read and display lines from the file until the end of
' the file is reached.
line = sr.ReadLine()
While (line <> Nothing)
Console.WriteLine(line)
line = sr.ReadLine()
End While
End Using
Catch e As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(e.Message)
End Try
Console.ReadKey()
End Sub
End Module
Guess what it displays when you compile and run the program!
VB.NET
The above list is not exhaustive. For complete list of methods please visit
Microsoft's documentation
Example
The following example demonstrates writing text data into a file using the
StreamWriter class:
Imports System.IO
Module fileProg
Sub Main()
Dim names As String() = New String() {"Zara Ali", _
182
VB.NET
Binary Files
The BinaryReader and BinaryWriter classes are used for reading from and
writing to a binary file.
183
VB.NET
The following table shows
the BinaryReaderclass.
S.N
some
of
the
commonly
used methods of
VB.NET
10
VB.NET
10
11
Example
The following example demonstrates reading and writing binary data:
Imports System.IO
Module fileProg
Sub Main()
Dim bw As BinaryWriter
Dim br As BinaryReader
Dim i As Integer = 25
Dim d As Double = 3.14157
Dim b As Boolean = True
Dim s As String = "I am happy"
'create the file
Try
186
VB.NET
VB.NET
CreationTime
Gets the creation time of the current file or directory.
Exists
Gets a Boolean value indicating whether the directory exists.
Extension
Gets the string representing the file extension.
188
VB.NET
FullName
Gets the full path of the directory or file.
LastAccessTime
Gets the time the current file or directory was last accessed.
Name
Gets the name of this DirectoryInfo instance.
Public
Function
CreateSubdirectory
(path
As
String)
As
DirectoryInfo
Creates a subdirectory or subdirectories on the specified path. The
specified path can be relative to this instance of the DirectoryInfo class.
3
For complete list of properties and methods please visit Microsoft's documentation.
189
VB.NET
S.N
1
CreationTime
Gets the creation time of the current file.
Directory
Gets an instance of the directory, which the file belongs to.
Exists
Gets a Boolean value indicating whether the file exists.
Extension
Gets the string representing the file extension.
FullName
Gets the full path of the file.
LastAccessTime
Gets the time the current file was last accessed.
LastWriteTime
Gets the time of the last written activity of the file.
Length
Gets the size, in bytes, of the current file.
10
Name
Gets the name of the file.
VB.NET
For complete list of properties and methods, please visit Microsoft's documentation
Example
The following example demonstrates the use of the above-mentioned classes:
Imports System.IO
Module fileProg
Sub Main()
'creating a DirectoryInfo object
Dim mydir As DirectoryInfo = New DirectoryInfo("c:\Windows")
' getting the files in the directory, their names and size
Dim f As FileInfo() = mydir.GetFiles()
191
VB.NET
", file.Name,
Next file
Console.ReadKey()
End Sub
End Module
When you compile and run the program, it displays the names of files and their
size in the Windows directory.
192
VB.NET
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 t,o 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:
193
VB.NET
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.
194
VB.NET
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:
S.N.
Forms
The container for all the controls that make up the user interface.
TextBox
It represents a Windows text box control.
Label
It represents a standard Windows label.
Button
It represents a Windows button control.
ListBox
It represents a Windows control to display a list of items.
ComboBox
It represents a Windows combo box control.
RadioButton
It enables the user to select a single option from a group of choices when
paired with other RadioButton controls.
CheckBox
It represents a Windows CheckBox.
PictureBox
It represents a Windows picture box control for displaying an image.
10
ProgressBar
It represents a Windows progress bar control.
195
VB.NET
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.
Forms
Let's start with creating a Window Forms Application by following the following
steps in Microsoft Visual Studio: File -> New Project -> Windows Forms
Applications
Finally, select OK, Microsoft Visual Studio creates your project and displays
following window Form with a name Form1.
196
VB.NET
Visual Basic Form is the container for all the controls that make up the user
interface. Every window you see in a running visual basic application is a form,
thus the terms form and window describe the same entity. Visual Studio creates
a default form for you when you create a Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there
will be buttons to close, maximize and minimize the form shown below:
197
VB.NET
If you click the icon on the top left corner, it opens the control menu, which
contains the various commands to control the form like to move control from one
place to another place, to maximize or minimize the form or to close the form.
Form Properties
Following table lists down various important properties related to a form. These
properties can be set or read during application execution. You can refer to
Microsoft documentation for a complete list of properties associated with a Form
control:
S.N
Properties
Description
AcceptButton
CancelButton
198
VB.NET
AutoScale
AutoScroll
AutoScrollMinSize
AutoScrollPosition
BackColor
BorderStyle
199
VB.NET
ControlBox
10
Enabled
11
Font
12
HelpButton
13
Height
14
MinimizeBox
15
MaximizeBox
16
MinimumSize
17
MaximumSize
18
Name
200
VB.NET
19
StartPosition
20
Text
21
Top, Left
22
TopMost
23
Width
Form Methods
The following are some of the commonly used methods of the Form class.You can
refer to Microsoft documentation for a complete list of methods associated with
forms control:
201
VB.NET
S.N.
Activate
Activates the form and gives it focus.
ActivateMdiChild
Activates the MDI child of a form.
AddOwnedForm
Adds an owned form to this form.
BringToFront
Brings the control to the front of the z-order.
CenterToParent
Centers the position of the form within the bounds of the parent form.
CenterToScreen
Centers the form on the current screen.
Close
Closes the form.
Contains
Retrieves a value indicating whether the specified control is a child of the
control.
Focus
Sets input focus to the control.
10
Hide
Conceals the control from the user.
11
Refresh
Forces the control to invalidate its client area and immediately redraw
itself and any child controls.
202
VB.NET
12
Scale(SizeF)
Scales the control and all child controls by the specified scaling factor.
13
ScaleControl
Scales the location, size, padding, and margin of a control.
14
ScaleCore
Performs scaling of the form.
15
Select
Activates the control.
16
SendToBack
Sends the control to the back of the z-order.
17
SetAutoScrollMargin
Sets the size of the auto-scroll margins.
18
SetDesktopBounds
Sets the bounds of the form in desktop coordinates.
19
SetDesktopLocation
Sets the location of the form in desktop coordinates.
20
SetDisplayRectLocation
Positions the display window to the specified value.
21
Show
Displays the control to the user.
22
ShowDialog
Shows the form as a modal dialog box.
Form Events
Following table lists down various important events related to a form. You can
refer to Microsoft documentation for a complete list of events associated with
forms control:
S.N
Event
Description
203
VB.NET
Activated
Click
Closed
Closing
DoubleClick
DragDrop
Occurs when
completed.
Enter
GotFocus
HelpButtonClicked
10
KeyDown
11
KeyPress
12
KeyUp
13
Load
14
LostFocus
drag-and-drop
operation
is
204
VB.NET
15
MouseDown
16
MouseEnter
17
MouseHover
18
MouseLeave
19
MouseMove
20
MouseUp
21
MouseWheel
22
Move
23
Resize
24
Scroll
25
Shown
26
VisibleChanged
Example
Following is an example, which shows how we create two buttons at the time of
form load event and different properties are being set at the same time.
205
VB.NET
Because Form1 is being referenced within its own event handler, so it will be
written as Me instead of using its name, but if we access the same form inside
any other control's event handler, then it will be accessed using its name Form1.
Let's double click on the Form and put the follow code in the opened window.
Public Class Form1
VB.NET
' Set the start position of the form to the center of the screen.
Me.StartPosition = FormStartPosition.CenterScreen
' Set window width and height
Me.Height = 300
Me.Width = 560
' Add button1 to the form.
Me.Controls.Add(button1)
' Add button2 to the form.
Me.Controls.Add(button2)
End Sub
End Class
When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:
TextBox Control
Text box controls allow entering text on a form at runtime. By default, it takes a
single line of text, however, you can make it accept multiple texts and even add
scroll bars to it.
Let's create a text box by dragging a Text Box control from the Toolbox and
dropping it on the form.
207
VB.NET
Property
Description
AcceptsReturn
AutoCompleteCustomSo
urce
Gets
or
sets
a
custom
System.Collections.Specialized.StringColle
ction
to
use
when
the
AutoCompleteSourceproperty is set to
CustomSource.
AutoCompleteMode
208
VB.NET
AutoCompleteSource
CharacterCasing
Font
FontHeight
ForeColor
Lines
10
Multiline
11
PasswordChar
12
ReadOnly
ScrollBars
None
Horizontal
Vertical
209
VB.NET
Both
14
TabIndex
15
Text
16
17
18
TextAlign
Left
Right
Center
TextLength
WordWrap
AppendText
Appends text to the current text of a text box.
Clear
Clears all text from the text box control.
Copy
Copies the current selection in the text box to the Clipboard.
Cut
Moves the current selection in the text box to the Clipboard.
Paste
210
VB.NET
Replaces the current selection in the text box with the contents of
the Clipboard.
6
Paste(String)
Sets the selected text to the specified text without clearing the undo
buffer.
ResetText
Resets the Text property to its default value.
ToString
Returns a string that represents the TextBoxBase control.
Undo
Undoes the last edit operation in the text box.
Event
Description
Click
DoubleClick
TextAlignChanged
Example
In this example, we create three text boxes and use the Click event of a button to
display the entered text using a message box. Take the following steps:
Drag and drop three Label controls and three TextBox controls on the form.
Change the texts on the labels to: Name, Organization and Comments,
respectively.
Change the names of the text boxes to txtName, txtOrg and txtComment,
respectively.
211
VB.NET
Drag and drop a button control on the form. Set its name to btnMessage
and its text property to 'Send Message'.
Click the button to add the Click event in the code window and add the
following code.
212
VB.NET
Clicking the Send Message button would show the following message box:
Label Control
The Label control represents a standard Windows label. It is generally used to
display some informative text on the GUI which is not changed during runtime.
Let's create a label by dragging a Label control from the Toolbox and dropping it
on the form.
Property
Description
Autosize
213
VB.NET
BorderStyle
FlatStyle
Font
FontHeight
ForeColor
PreferredHeight
PreferredWidth
TabStop
10
Text
11
TextAlign
GetPreferredSize
Retrieves the size of a rectangular area into which a control can be fitted.
Refresh
214
VB.NET
Forces the control to invalidate its client area and immediately redraw
itself and any child controls.
3
Select
Activates the control.
Show
Displays the control to the user.
ToString
Returns a String that contains the name of the control.
Event
Description
AutoSizeChanged
Click
DoubleClick
GotFocus
Leave
LostFocus
TabIndexChanged
TabStopChanged
215
VB.NET
TextChanged
Refer the Microsoft documentation for a detailed list of properties, methods and
events of the Label control.
Example
Following is an example, which shows how we can create two labels. Let us create
the first label from the designer view tab and set its properties from the properties
window. We will use the Click and the DoubleClick events of the label to move the
first label and change its text and create the second label and add it to the form,
respectively.
Take the following steps:
1. Drag and drop a Label control on the form.
2. Set the Text property to provide the caption "This is a Label Control".
3. Set the Font property from the properties window.
4. Click the label to add the Click event in the code window and add the
following codes.
Public Class Form1
VB.NET
Clicking and double clicking the label would produce the following effect:
217
VB.NET
Button Control
The Button control represents a standard Windows button. It is generally used to
generate a Click event by providing a handler for the Click event.
Let's create a label by dragging a Button control from the Toolbox ad dropping it
on the form.
VB.NET
S.N
Property
Description
AutoSizeMode
BackColor
BackgroundImage
DialogResult
ForeColor
Image
Location
TabIndex
Text
219
VB.NET
GetPreferredSize
Retrieves the size of a rectangular area into which a control can be fitted.
NotifyDefault
Notifies the Button whether it is the default button so that it can adjust
its appearance accordingly.
Select
Activates the control.
ToString
Returns a String containing the name of the Component, if any. This
method should not be overridden.
Event
Description
Click
DoubleClick
GotFocus
TabIndexChanged
TextChanged
Validated
Example
In the following example, we create three buttons. In this example, let us:
220
VB.NET
Using the properties window, change the Name properties of the buttons to
btnMoto, btnLogo and btnExit respectively.
Using the properties window, change the Text properties of the buttons to
Show Moto, Show Logo and Exit respectively.
Drag and Drop another button, using the properties window, set its Image
property and name it btnImage.
Click the form and add following code in the code editor:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
221
VB.NET
VB.NET
ListBox Control
The ListBox represents a Windows control to display a list of items to a user. A
user can select an item from the list. It allows the programmer to add items at
design time by using the properties window or at the runtime.
Let's create a list box by dragging a ListBox control from the Toolbox and dropping
it on the form.
223
VB.NET
You can populate the list box items either from the properties window or at
runtime. To add items to a ListBox, select the ListBox control and get to the
properties window, for the properties of this control. Click the ellipses (...) button
next to the Items property. This opens the String Collection Editor dialog box,
where you can enter the values one at a line.
Property
Description
AllowSelection
BorderStyle
ColumnWidth
HorizontalExtent
HorizontalScrollBar
ItemHeight
Items
MultiColumn
ScrollAlwaysVisible
224
VB.NET
10
SelectedIndex
11
SelectedIndices
12
SelectedItem
13
SelectedItems
14
SelectedValue
15
SelectionMode
None
One
MultiSimple
MultiExtended
16
Sorted
17
Text
18
TopIndex
225
VB.NET
S.N
BeginUpdate
Prevents the control from drawing until the EndUpdate method is called,
while items are added to the ListBox one at a time.
ClearSelected
Unselects all items in the ListBox.
EndUpdate
Resumes drawing of a list box after it was turned off by the BeginUpdate
method.
FindString
Finds the first item in the ListBox that starts with the string specified as
an argument.
FindStringExact
Finds the first item in the ListBox that exactly matches the specified
string.
GetSelected
Returns a value indicating whether the specified item is selected.
SetSelected
Selects or clears the selection for the specified item in a ListBox.
OnSelectedIndexChanged
Raises the SelectedIndexChanged event.
OnSelectedValueChanged
Raises the SelectedValueChanged event.
Description
Click
226
VB.NET
SelectedIndexChanged
Example 1
In the following example, let us add a list box at design time and add items on it
at runtime.
Take the following steps:
Drag and drop two labels, a button and a ListBox control on the form.
Set the Text property of the first label to provide the caption "Choose your
favourite destination for higher studies".
Set the Text property of the second label to provide the caption "Destination".
The text on this label will change at runtime when the user selects an item
on the list.
Click the listbox and the button controls to add the following codes in the code
editor.
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"
ListBox1.Items.Add("Canada")
ListBox1.Items.Add("USA")
ListBox1.Items.Add("UK")
ListBox1.Items.Add("Japan")
ListBox1.Items.Add("Russia")
ListBox1.Items.Add("China")
ListBox1.Items.Add("India")
End Sub
VB.NET
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As
EventArgs)
Handles ListBox1.SelectedIndexChanged
Label2.Text = ListBox1.SelectedItem.ToString()
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:
When the user chooses a destination, the text in the second label changes:
228
VB.NET
Clicking the Select button displays a message box with the user's choice:
Example 2
In this example, we will fill up a list box with items, retrieve the total number of
items in the list box, sort the list box, remove some items and clear the entire list
box.
Design the Form:
229
VB.NET
VB.NET
VB.NET
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:
ComboBox Control
The ComboBox control is used to display a drop-down list of various items. It is a
combination of a text box in which the user enters an item and a drop-down list
from which the user selects an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and
dropping it on the form.
232
VB.NET
You can populate the list box items either from the properties window or at
runtime. To add items to a ListBox, select the ListBox control and go to the
properties window for the properties of this control. Click the ellipses (...) button
next to the Items property. This opens the String Collection Editor dialog box,
where you can enter the values one at a line.
Property
Description
AllowSelection
AutoCompleteCustomSource
233
VB.NET
AutoCompleteMode
AutoCompleteSource
DataBindings
DataManager
DataSource
DropDownHeight
DropDownStyle
10
DropDownWidth
11
DroppedDown
12
FlatStyle
13
ItemHeight
234
VB.NET
14
Items
15
MaxDropDownItems
16
MaxLength
17
SelectedIndex
18
SelectedItem
19
SelectedText
20
SelectedValue
21
SelectionLength
22
SelectionStart
23
Sorted
235
VB.NET
24
Text
BeginUpdate
Prevents the control from drawing until the EndUpdate method is called,
while items are added to the combo box one at a time.
EndUpdate
Resumes drawing of a combo box, after it was turned off by the
BeginUpdate method.
FindString
Finds the first item in the combo box that starts with the string specified
as an argument.
FindStringExact
Finds the first item in the combo box that exactly matches the specified
string.
SelectAll
Selects all the text in the editable area of the combo box.
236
VB.NET
S.N
Event
Description
DropDown
DropDownClosed
DropDownStyleChanged
Occurs
when
the
DropDownStyle
property of the ComboBox has changed.
SelectedIndexChanged
SelectionChangeCommitted
Example
In this example, let us fill a combo box with various items, get the selected items
in the combo box and show them in a list box and sort the items.
Drag and drop a combo box to store the items, a list box to display the selected
items, four button controls to add to the list box with selected items, to fill the
combo box, to sort the items and to clear the combo box list, respectively.
Add a label control that would display the selected item.
237
VB.NET
VB.NET
ComboBox1.Items.Clear()
ComboBox1.Items.Add("Safety")
ComboBox1.Items.Add("Security")
ComboBox1.Items.Add("Governance")
ComboBox1.Items.Add("Good Music")
ComboBox1.Items.Add("Good Movies")
ComboBox1.Items.Add("Good Books")
ComboBox1.Items.Add("Education")
ComboBox1.Items.Add("Roads")
ComboBox1.Items.Add("Health")
ComboBox1.Items.Add("Food for all")
ComboBox1.Items.Add("Shelter for all")
ComboBox1.Items.Add("Industrialisation")
ComboBox1.Items.Add("Peace")
ComboBox1.Items.Add("Liberty")
ComboBox1.Items.Add("Freedom of Speech")
ComboBox1.Text = "Select from..."
End Sub
'sorting the list
Private Sub Button3_Click(sender As Object, e As EventArgs)
ComboBox1.Sorted = True
End Sub
'clears the list
Private Sub Button4_Click(sender As Object, e As EventArgs)
ComboBox1.Items.Clear()
End Sub
'displaying the selected item on the label
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As
EventArgs) _
Handles ListBox1.SelectedIndexChanged
Label1.Text = ComboBox1.SelectedItem.ToString()
End Sub
End Class
239
VB.NET
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:
RadioButton Control
The RadioButton control is used to provide a set of mutually exclusive options.
The user can select one radio button in a group. If you need to place more than
one group of radio buttons in the same form, you should place them in different
container controls like a GroupBox control.
240
VB.NET
Let's create three radio buttons by dragging RadioButton controls from the Toolbox
and dropping on the form.
The Checked property of the radio button is used to set the state of a radio button.
You can display text, image or both on radio button control. You can also change
the appearance of the radio button control by using the Appearance property.
Property
Description
Appearance
AutoCheck
CheckAlign
Checked
241
VB.NET
Text
TabStop
PerformClick
Generates a Click event for the control, simulating a click by a user.
Event
Description
AppearanceChanged
CheckedChanged
Example
In the following example, let us create two groups of radio buttons and use their
CheckedChanged events for changing the BackColor and ForeColor property of the
form.
242
VB.NET
Let's double click on the radio buttons and put the follow code in the opened
window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
VB.NET
CheckBox Control
The CheckBox control allows the user to set true/false or yes/no type options. The
user can select or deselect it. When a check box is selected it has the value True,
and when it is cleared, it holds the value False.
Let's create two check boxes by dragging CheckBox controls from the Toolbox and
dropping on the form.
244
VB.NET
Property
Description
Appearance
AutoCheck
CheckAlign
Checked
245
VB.NET
CheckState
Text
ThreeState
OnCheckedChanged
Raises the CheckedChanged event.
OnCheckStateChanged
Raises the CheckStateChanged event.
OnClick
Raises the OnClick event.
Event
Description
AppearanceChanged
CheckedChanged
CheckStateChanged
246
VB.NET
Example
In this example, let us add four check boxes in a group box. The check boxes will
allow the users to choose the source from which they came to know about the
organization. If the user chooses the check box with text "others", then the user
is asked to specify and a text box is provided to give input. When the user clicks
the Submit button, he/she gets an appropriate message.
The form in design view:
VB.NET
248
VB.NET
249
VB.NET
PictureBox Control
The PictureBox control is used for displaying images on the form. The Image
property of the control allows you to set an image both at design time or at run
time.
Let's create a picture box by dragging a PictureBox control from the Toolbox and
dropping it on the form.
Property
Description
AllowDrop
ErrorImage
Image
250
VB.NET
ImageLocation
InitialImage
SizeMode
TabIndex
TabStop
Text
WaitOnLoad
Specifies whether
synchronously.
10
or
not
an
image
is
loaded
251
VB.NET
CancelAsync
Cancels an asynchronous image load.
Load
Displays an image in the picture box
LoadAsync
Loads image asynchronously.
ToString
Returns the string that represents the current picture box.
Event
Description
CausesValidationChanged
Overrides the
Control.CausesValidationChanged
property.
Click
Enter
FontChanged
ForeColorChanged
KeyDown
252
VB.NET
KeyPress
KeyUp
Leave
Occurs when
PictureBox.
10
LoadCompleted
11
LoadProgressChanged
12
Resize
13
RightToLeftChanged
14
SizeChanged
15
SizeModeChanged
16
TabIndexChanged
17
TabStopChanged
18
TextChanged
input
focus
leaves
the
Example
In this example, let us put a picture box and a button control on the form. We set
the image property of the picture box to logo.png, as we used before. The Click
253
VB.NET
event of the button named Button1 is coded to stretch the image to a specified
size:
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 = "tutorialspoint.com"
End Sub
254
VB.NET
255
VB.NET
ProgressBar Control
It represents a Windows progress bar control. It is used to provide visual feedback
to your users about the status of some task. It shows a bar that fills in from left
to right as the operation progresses.
Let's click on a ProgressBar control from the Toolbox and place it on the form.
The main properties of a progress bar are Value, Maximum and Minimum. The
Minimum and Maximum properties are used to set the minimum and maximum
values that the progress bar can display. The Value property specifies the current
position of the progress bar.
The ProgressBar control is typically used when an application performs tasks such
as copying files or printing documents. To a user the application might look
unresponsive if there is no visual cue. In such cases, using the ProgressBar allows
the programmer to provide a visual status of progress.
Property
Description
AllowDrop
Overrides Control.AllowDrop.
BackgroundImage
VB.NET
BackgroundImageLayout
CausesValidation
Font
ImeMode
ImeModeBase
MarqueeAnimationSpeed
Maximum
10
Minimum
11
Padding
12
RightToLeftLayout
13
Step
14
Style
257
VB.NET
15
Value
Increment
Increments the current position of the ProgressBar control by specified
amount.
PerformStep
Increments the value by the specified step.
ResetText
Resets the Text property to its default value.
ToString
Returns a string that represents the progress bar control.
Event
Description
BackgroundImageChanged
BackgroundImageLayoutCha
nged
CausesValidationChanged
VB.NET
Click
DoubleClick
Enter
FontChanged
ImeModeChanged
KeyDown
10
KeyPress
11
KeyUp
12
Leave
13
MouseClick
14
MouseDoubleClick
15
PaddingChanged
16
Paint
Occurs
drawn.
17
RightToLeftLayoutChanged
when
the
of
leaves
ProgressBar
the
the
is
259
VB.NET
18
TabStopChanged
18
TextChanged
Occurs when
changes.
the
Text
property
Example
In this example, let us create a progress bar at runtime. Let's double click on the
Form and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'create two progress bars
Dim ProgressBar1 As ProgressBar
Dim ProgressBar2 As ProgressBar
ProgressBar1 = New ProgressBar()
ProgressBar2 = New ProgressBar()
'set position
ProgressBar1.Location = New Point(10, 10)
ProgressBar2.Location = New Point(10, 50)
'set values
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 200
ProgressBar1.Value = 130
ProgressBar2.Minimum = 0
ProgressBar2.Maximum = 100
ProgressBar2.Value = 40
'add the progress bar to the form
Me.Controls.Add(ProgressBar1)
Me.Controls.Add(ProgressBar2)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
End Class
260
VB.NET
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:
ScrollBar Control
The ScrollBar controls display vertical and horizontal scroll bars on the form. This
is used for navigating through large amount of information. There are two types
of scroll bar controls: HScrollBar for horizontal scroll bars and VScrollBar for
vertical scroll bars. These are used independently from each other.
Let's click on HScrollBar control and VScrollBar control from the Toolbox and place
them on the form.
261
VB.NET
Property
Description
AutoSize
BackColor
ForeColor
ImeMode
LargeChange
Maximum
Minimum
SmallChange
Value
262
VB.NET
OnClick
Generates the Click event.
Select
Activates the control.
Event
Description
Click
DoubleClick
Scroll
ValueChanged
Example
In this example, let us create two scroll bars at runtime. Let's double click on the
Form and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'create two scroll bars
Dim hs As HScrollBar
Dim vs As VScrollBar
hs = New HScrollBar()
263
VB.NET
vs = New VScrollBar()
'set properties
hs.Location = New Point(10, 200)
hs.Size = New Size(175, 15)
hs.Value = 50
vs.Location = New Point(200, 30)
vs.Size = New Size(15, 175)
hs.Value = 50
'adding the scroll bars to the form
Me.Controls.Add(hs)
Me.Controls.Add(vs)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
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:
DateTimePicker Control
The DateTimePicker control allows selecting a date and time by editing the
displayed values in the control. If you click the arrow in the DateTimePicker
control, it displays a month calendar, like a combo box control. The user can make
selection by clicking the required date. The new selected value appears in the text
box part of the control.
264
VB.NET
The MinDate and the MaxDate properties allow you to put limits on the date
range.
Property
Description
BackColor
BackgroundImage
BackgroundImageLayout
CalendarFont
CalendarForeColor
VB.NET
CalendarMonthBackground
CalendarTitleBackColor
CalendarTitleForeColor
CalendarTrailingForeColor
10
Checked
11
CustomFormat
12
DropDownAlign
13
ForeColor
14
Format
15
MaxDate
16
MaximumDateTime
17
MinDate
18
MinimumDateTime
VB.NET
19
PreferredHeight
20
RightToLeftLayout
21
ShowCheckBox
22
ShowUpDown
23
Text
24
Value
of
the
ToString
Returns the string representing the control.
Event
Description
BackColorChanged
VB.NET
BackgroundImageChanged
BackgroundImageLayoutChanged
Click
Occurs when
clicked.
the
CloseUp
Occurs when
calendar
is
disappears.
the drop-down
dismissed
and
DoubleClick
DragDrop
ForeColorChanged
FormatChanged
10
MouseClick
11
MouseDoubleClick
12
PaddingChanged
13
Paint
Occurs when
redrawn.
the
control
control
control
is
is
is
268
VB.NET
14
RightToLeftLayoutChanged
Occurs
when
RightToLeftLayout
changes.
15
TextChanged
16
ValueChanged
the
property
Example
In this example, let us create a small application for calculating days of leave. Let
us add two DateTimePicker controls on the form, where the user will enter the
date of going on leave and the date of joining. Let us keep a button control for
performing the calculation and appropriate label controls for displaying
information.
The form in design view:
VB.NET
Select two dates and click on the button for leave calculation:
TreeView Control
The TreeView control is used to display hierarchical representations of items
similar to the ways the files and folders are displayed in the left pane of the
Windows Explorer. Each node may contain one or more child nodes.
270
VB.NET
Let's click on a TreeView control from the Toolbox and place it on the form.
Property
Description
BackColor
BackgroundImage
BackgroundImageLayout
BorderStyle
CheckBoxes
271
VB.NET
DataBindings
Font
FontHeight
ForeColor
10
ItemHeight
11
Nodes
12
PathSeparator
13
RightToLeftLayout
14
Scrollable
15
SelectedImageIndex
16
SelectedImageKey
17
SelectedNode
272
VB.NET
18
ShowLines
19
ShowNodeToolTips
20
ShowPlusMinus
21
ShowRootLines
22
Sorted
23
StateImageList
24
Text
25
TopNode
26
TreeViewNodeSorter
27
VisibleCount
273
VB.NET
S.N
CollapseAll
Collapses all the nodes including all child nodes in the tree view control.
ExpandAll
Expands all the nodes.
GetNodeAt
Gets the node at the specified location.
GetNodeCount
Gets the number of tree nodes.
Sort
Sorts all the items in the tree view control.
ToString
Returns a string containing the name of the control.
Event
Description
AfterCheck
AfterCollapse
AfterExpand
AfterSelect
BeforeCheck
BeforeCollapse
BeforeExpand
VB.NET
BeforeLabelEdit
BeforeSelect
10
ItemDrag
11
NodeMouseClick
12
NodeMouseDou
bleClick
13
NodeMouseHove
r
14
PaddingChange
d
15
Paint
16
RightToLeftLayo
utChanged
17
TextChanged
Property
Description
BackColor
275
VB.NET
Checked
ContextMenu
ContextMenuStrip
FirstNode
FullPath
Gets the path from the root tree node to the current
tree node.
Index
IsEditing
IsExpanded
10
IsSelected
11
IsVisible
12
LastNode
13
Level
14
Name
15
NextNode
276
VB.NET
16
Nodes
17
Parent
18
PrevNode
19
PrevVisibleNode
20
Tag
21
Text
22
ToolTipText
23
TreeView
Collapse
Collapses the tree node.
Expand
Expands the tree node.
ExpandAll
Expands all the child tree nodes.
GetNodeCount
Returns the number of child tree nodes.
277
VB.NET
Remove
Removes the current tree node from the tree view control.
Toggle
Toggles the tree node to either the expanded or collapsed state.
ToString
Returns a string that represents the current object.
Example
In this example, let us create a tree view at runtime. Let's double click on the
Form and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
'create a new TreeView
Dim TreeView1 As TreeView
TreeView1 = New TreeView()
TreeView1.Location = New Point(10, 10)
TreeView1.Size = New Size(150, 150)
Me.Controls.Add(TreeView1)
TreeView1.Nodes.Clear()
'Creating the root node
Dim root = New TreeNode("Application")
TreeView1.Nodes.Add(root)
TreeView1.Nodes(0).Nodes.Add(New TreeNode("Project 1"))
'Creating child nodes under the first child
For loopindex As Integer = 1 To 4
TreeView1.Nodes(0).Nodes(0).Nodes.Add(New
VB.NET
TreeView1.Nodes(0).Nodes(1).Nodes.Add(New
279
VB.NET
ListView Control
The ListView control is used to display a list of items. Along with the TreeView
control, it allows you to create a Windows Explorer like interface. Let's click on a
ListView control from the Toolbox and place it on the form.
The ListView control displays a list of items along with icons. The Item property of
the ListView control allows you to add and remove items from it.
The SelectedItem property contains a collection of the selected items.
The MultiSelect property allows you to set select more than one item in the list
view. The CheckBoxes property allows you to set check boxes next to the items.
Property
Description
Alignment
AutoArrange
BackColor
280
VB.NET
CheckBoxes
CheckedIndices
CheckedItems
Columns
GridLines
HeaderStyle
10
HideSelection
11
HotTracking
12
HoverSelection
13
InsertionMark
14
Items
281
VB.NET
15
LabelWrap
16
LargeImageList
17
MultiSelect
18
RightToLeftLayout
19
Scrollable
20
SelectedIndices
21
SelectedItems
22
ShowGroups
23
ShowItemToolTips
24
SmallImageList
25
Sorting
282
VB.NET
26
StateImageList
27
TopItem
28
View
with
29
VirtualListSize
30
VirtualMode
Clear
Removes all items from the ListView control.
ToString
Returns a string containing the string representation of the control.
283
VB.NET
Event
Description
ColumnClick
ItemCheck
SelectedIndexChanged
TextChanged
Example
In this example, let us create a list view at runtime. Let's double click on the Form
and put the follow code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
'create a new ListView
Dim ListView1 As ListView
ListView1 = New ListView()
ListView1.Location = New Point(10, 10)
ListView1.Size = New Size(150, 150)
Me.Controls.Add(ListView1)
'Creating the list items
Dim ListItem1 As ListViewItem
ListItem1 = ListView1.Items.Add("Item 1")
Dim ListItem2 As ListViewItem
284
VB.NET
285
VB.NET
There are many built-in dialog boxes to be used in Windows forms for various
tasks like opening and saving files, printing a page, providing choices for colors,
fonts, page setup, etc., to the user of an application. These built-in dialog boxes
reduce the developer's time and workload.
All of these dialog box control classes inherit from the CommonDialog class and
override the RunDialog() function of the base class to create the specific dialog
box.
The RunDialog() function is automatically invoked when a user of a dialog box
calls its ShowDialog() function.
The ShowDialog method is used to display all the dialog box controls at run-time.
It returns a value of the type of DialogResult enumeration. The values of
DialogResult enumeration are:
Abort - returns DialogResult.Abort value, when user clicks an Abort button.
Cancel- returns DialogResult.Cancel, when user clicks a Cancel button.
Ignore - returns DialogResult.Ignore, when user clicks an Ignore button.
No - returns DialogResult.No, when user clicks a No button.
None - returns nothing and the dialog box continues running.
OK - returns DialogResult.OK, when user clicks an OK button
Retry - returns DialogResult.Retry , when user clicks a Retry button
Yes - returns DialogResult.Yes, when user clicks an Yes button
286
VB.NET
The following diagram shows the common dialog class inheritance:
ColorDialog
It represents a common dialog box that displays available colors along
with controls that enable the user to define custom colors.
FontDialog
It prompts the user to choose a font from among those installed on the
local computer and lets the user select the font, font size, and color.
OpenFileDialog
It prompts the user to open a file and allows the user to select a file to
open.
SaveFileDialog
It prompts the user to select a location for saving a file and allows the
user to specify the name of the file to save data.
287
VB.NET
PrintDialog
It lets the user to print documents by selecting a printer and choosing
which sections of the document to print from a Windows Forms
application.
ColorDialog Control
The ColorDialog control class represents a common dialog box that displays
available colors along with controls that enable the user to define custom colors.
It lets the user select a color.
The main property
a Color object.
of
the
ColorDialog
control
is Color,
which
returns
Property
Description
AllowFullOpen
VB.NET
AnyColor
CanRaiseEvents
Color
CustomColors
FullOpen
ShowHelp
SolidColorOnly
Reset
Resets all options to their default values, the last selected color to black,
and the custom colors to their default values.
RunDialog
When overridden in a derived class, specifies a common dialog box.
ShowDialog
Runs a common dialog box with a default owner.
289
VB.NET
Event
Description
HelpRequest
Example
In this example, let's change the forecolor of a label control using the color dialog
box. Take the following steps:
Drag and drop a label control, a button control and a ColorDialog control on
the form.
Set the Text property of the label and the button control to 'Give me a new
Color' and 'Change Color', respectively.
Double-click the Change Color button and modify the code of the Click
event.
290
VB.NET
Clicking on the Change Color button, the color dialog appears, select a color and
click the OK button. The selected color will be applied as the forecolor of the text
of the label.
FontDialog Control
It prompts the user to choose a font from among those installed on the local
computer and lets the user select the font, font size, and color. It returns the Font
and Color objects.
Following is the Font dialog box:
By default, the Color ComboBox is not shown on the Font dialog box. You should
set the ShowColor property of the FontDialog control to be True.
291
VB.NET
Property
Description
AllowSimulations
AllowVectorFonts
AllowVerticalFonts
Color
FixedPitchOnly
Font
FontMustExist
MaxSize
MinSize
10
ScriptsOnly
11
ShowApply
VB.NET
12
ShowColor
13
ShowEffects
14
ShowHelp
Reset
Resets all options to their default values.
RunDialog
When overridden in a derived class, specifies a common dialog box.
ShowDialog
Runs a common dialog box with a default owner.
Event
Description
Apply
Example
In this example, let's change the font and color of the text from a rich text control
using the Font dialog box. Take the following steps:
VB.NET
Double-click the Change Color button and modify the code of the Click event:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
If FontDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then
RichTextBox1.ForeColor = FontDialog1.Color
RichTextBox1.Font = FontDialog1.Font
End If
End Sub
When the application is compiled and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window:
294
VB.NET
The Font dialog appears, select a font and a color and click the OK button. The
selected font and color will be applied as the font and fore color of the text of the
rich text box.
OpenFileDialog Control
The OpenFileDialog control prompts the user to open a file and allows the user
to select a file to open. The user can check if the file exists and then open it. The
OpenFileDialog control class inherits from the abstract class FileDialog.
If the ShowReadOnly property is set to True, then a read-only check box appears
in the dialog box. You can also set the ReadOnlyChecked property to True, so that
the read-only check box appears checked.
Following is the Open File dialog box:
295
VB.NET
Property
Description
AddExtension
AutoUpgradeEnabled
CheckFileExists
CheckPathExists
CustomPlaces
DefaultExt
DereferenceLinks
FileName
VB.NET
FileNames
10
Filter
11
FilterIndex
12
InitialDirectory
13
Multiselect
14
ReadOnlyChecked
15
RestoreDirectory
16
SafeFileName
17
SafeFileNames
18
ShowHelp
297
VB.NET
19
ShowReadOnly
20
SupportMultiDottedExtensions
21
Title
22
ValidateNames
OpenFile
Opens the file selected by the user, with read-only permission. The file is
specified by the FileName property.
Reset
Resets all options to their default value.
Example
In this example, let's load an image file in a picture box, using the open file dialog
box. Take the following steps:
Set the Text property of the button control to 'Load Image File'.
Double-click the Load Image File button and modify the code of the Click
event.
298
VB.NET
Click on the Load Image File button to load an image stored in your computer.
299
VB.NET
SaveFileDialog Control
The SaveFileDialog control prompts the user to select a location for saving a file
and allows the user to specify the name of the file to save data. The SaveFileDialog
control class inherits from the abstract class FileDialog.
Following is the Save File dialog box:
Property
Description
AddExtension
CheckFileExists
300
VB.NET
CheckPathExists
CreatePrompt
Gets or sets a
whether the dialog
user for permission
the user specifies a
exist.
DefaultExt
DereferenceLinks
FileName
FileNames
Filter
10
FilterIndex
11
InitialDirectory
12
OverwritePrompt
value indicating
box prompts the
to create a file if
file that does not
301
VB.NET
RestoreDirectory
14
ShowHelp
15
SupportMultiDottedExtensions
16
Title
17
ValidateNames
OpenFile
Opens the file with read/write permission.
Reset
Resets all dialog box options to their default values.
Example
In this example, let's save the text entered into a rich text box by the user using
the save file dialog box. Take the following steps:
Drag and drop a Label control, a RichTextBox control, a Button control and
a SaveFileDialog control on the form.
302
VB.NET
Set the Text property of the label and the button control to 'We appreciate
your comments' and 'Save Comments', respectively.
Double-click the Save Comments button and modify the code of the Click
event as shown:
We have set the Filter property of the SaveFileDialog control to display text file
types with .txt extensions only.
Write some text in the text box and click on the Save Comment button to save
the text as a text file in your computer.
PrintDialog Control
The PrintDialog control lets the user to print documents by selecting a printer and
choosing which sections of the document to print from a Windows Forms
application.
303
VB.NET
There are various other controls related to printing of documents. Let us have a
brief look at these controls and their purpose. These other controls are:
304
VB.NET
Property
Description
AllowCurrentPage
AllowPrintToFile
AllowSelection
whether
AllowSomePages
whether
Document
PrinterSettings
PrintToFile
ShowHelp
indicating
whether
ShowNetwork
whether
VB.NET
RunDialog
When overridden in a derived class, specifies a common dialog box.
ShowDialog
Runs a common dialog box with a default owner.
Example
In this example, let us see how to show a Print dialog box in a form. Take the
following steps:
Double-click the Print button and modify the code of the Click event as
shown:
When the application is compiled and run using Start button available at
the Microsoft Visual Studio tool bar, it will show the following window:
306
VB.NET
Click the Print button to make the Print dialog box appear.
307
VB.NET
Modal forms
VB.NET
mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)
309
VB.NET
Windows Forms contain a rich set of classes for creating your own custom menus
with modern appearance, look and feel. The MenuStrip, ToolStripMenuItem,
ContextMenuStrip controls are used to create menu bars and context menus
efficiently.
Click the following links to check their details:
S.N.
MenuStrip
It provides a menu system for a form.
ToolStripMenuItem
It represents a selectable option displayed on a MenuStrip or
ContextMenuStrip. The ToolStripMenuItem control replaces and adds
functionality to the MenuItem control of previous versions.
ContextMenuStrip
It represents a shortcut menu.
MenuStrip Control
The MenuStrip control represents the container for the menu structure.
MenuStrip control works as the top-level container for the menu structure.
ToolStripMenuItem class and the ToolStripDropDownMenu class provide
functionalities to create menu items, sub menus and drop-down menus.
following diagram shows adding a MenuStrip control on the form:
The
The
the
The
310
VB.NET
Property
Description
CanOverflow
GripStyle
MdiWindowListItem
ShowItemToolTips
311
VB.NET
Stretch
Event
Description
MenuActivate
MenuDeactivate
Example
In this example, let us add menu and sub-menu items.
Take the following steps:
Drag and drop or double click on a MenuStrip control, to add it to the form.
Click the Type Here text to open a text box and enter the names of the
menu items or sub-menu items you want. When you add a sub-menu,
another text box with 'Type Here' text opens below it.
312
VB.NET
Double-Click the Exit menu created and add the following code to
the Click event of ExitToolStripMenuItem:
313
VB.NET
StripMenuItem Control
The ToolStripMenuItem class supports the menus and menu items in a menu
system. You handle these menu items through the click events in a menu system.
Property
Description
Checked
CheckOnClick
CheckState
Enabled
IsMdiWindowListEntry
VB.NET
ShortcutKeyDisplayString
ShortcutKeys
ShowShortcutKeys
Event
Description
CheckedChanged
CheckStateChanged
value
of the
CheckState
Example
In this example, let us continue with the example from the chapter 'VB.Net MenuStrip control'. Let us:
VB.NET
Handles MyBase.Load
' Hide the project menu
ProjectToolStripMenuItem1.Visible = False
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
Add a button control on the form with text 'Show Project'.
Add the following code snippet to the Button1_Click event:
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
ProjectToolStripMenuItem1.Visible = True
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:
316
VB.NET
317
VB.NET
VB.NET
Select the Edit menu item and select its ShortcutKeys property in the properties
window.
Click the drop down button next to it.
Select Ctrl as Modifier and E as the key.
ContextMenuStrip Control
The ContextMenuStrip control represents a shortcut menu that pops up over
controls, usually when you right click them. They appear in context of some
specific controls, so are called context menus. For example, Cut, Copy or Paste
options.
This control associates the context menu with other menu items by setting that
menu item's ContextMenuStrip property to the ContextMenuStrip control you
designed.
Context menu items can also be disabled, hidden, or deleted. You can also show
a context menu with the help of the Show method of the ContextMenuStrip
control.
The following diagram shows adding a ContextMenuStrip control on the form:
319
VB.NET
Property
Description
SourceControl
Gets
the
last
control
ContextMenuStrip control.
that
displayed
the
Example
In this example, let us add a content menu with the menu items Cut, Copy and
Paste.
Take the following steps:
rich
text
box
to
320
VB.NET
Double the menu items and add following codes in the Click event of these
menus:
321
VB.NET
Enter some text in the rich text box, select it and right-click to get the context
menu appear:
Now, you can select any menu items and perform cut, copy or paste on the text
box.
Clear
Removes all data from the Clipboard.
ContainsData
Indicates whether there is data on the Clipboard that is in the specified
format or can be converted to that format.
ContainsImage
Indicates whether there is data on the Clipboard that is in the Bitmap
format or can be converted to that format.
ContainsText
322
VB.NET
GetData
Retrieves data from the Clipboard in the specified format.
GetDataObject
Retrieves the data that is currently on the system Clipboard.
GetImage
Retrieves an image from the Clipboard.
GetText
Retrieves text data from the Clipboard in the Text or UnicodeText format,
depending on the operating system.
GetText(TextDataFormat)
Retrieves text data from the Clipboard in the format indicated by the
specified TextDataFormat value.
10
SetData
Clears the Clipboard and then adds data in the specified format.
11
SetText(String)
Clears the Clipboard and then adds text data in the Text or UnicodeText
format, depending on the operating system.
Following is an example, which shows how we cut, copy and paste data using
methods of the Clipboard class. Take the following steps:
Add a rich text box control and three button controls on the form.
Change the text property of the buttons to Cut, Copy and Paste,
respectively.
Double click on the buttons to add the following code in the code editor:
VB.NET
Me.Text = "tutorialspoint.com"
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Clipboard.SetDataObject(RichTextBox1.SelectedText)
RichTextBox1.SelectedText = ""
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) _
Handles Button2.Click
Clipboard.SetDataObject(RichTextBox1.SelectedText)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) _
Handles Button3.Click
Dim iData As IDataObject
iData = Clipboard.GetDataObject()
If (iData.GetDataPresent(DataFormats.Text)) Then
RichTextBox1.SelectedText = iData.GetData(DataFormats.Text)
Else
RichTextBox1.SelectedText = " "
End If
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:
324
VB.NET
325
VB.NET
For example, let us add a Button control on a form and set its anchor property to
Bottom, Right. Run this form to see the original position of the Button control with
respect to the form.
Now, when you stretch the form, the distance between the Button and the bottom
right corner of the form remains same.
326
VB.NET
For example, let us add a Button control on a form and set its Dock property to
Bottom. Run this form to see the original position of the Button control with respect
to the form.
Now, when you stretch the form, the Button resizes itself with the form.
327
VB.NET
Modal Forms
Modal Forms are those forms that need to be closed or hidden before you can
continue working with the rest of the application. All dialog boxes are modal forms.
A MessageBox is also a modal form.
You can call a modal form by two ways:
Let us take up an example in which we will create a modal form, a dialog box.
Take the following steps:
Add a form, Form1 to your application, and add two labels and a button
control to Form1
Change the text properties of the first label and the button to 'Welcome to
Tutorials Point' and 'Enter your Name', respectively. Keep the text
properties of the second label as blank.
Add a new Windows Form, Form2, and add two buttons, one label, and a
text box to Form2.
328
VB.NET
Set the DialogResult property of the OK button to OK and the Cancel button
to Cancel.
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:
329
VB.NET
Clicking on the 'Enter your Name' button displays the second form:
Clicking on the OK button takes the control and information back from the
modal form to the previous form:
330
VB.NET
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
MouseHover - it occurs when the mouse pointer hovers over 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
VB.NET
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.
VB.NET
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:
333
VB.NET
Try to enter text in the text boxes and check the mouse events:
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:
VB.NET
Modifiers - it indicates which modifier keys (Ctrl, Shift, and/or Alt) are
pressed
The event handlers of the KeyDown and KeyUp events get an argument of type
KeyEventArgs. This object has the following properties:
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.
VB.NET
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:
336
VB.NET
337
VB.NET
Character Escapes
These are basically the special characters or escape characters. The backslash
character (\) in a regular expression indicates that the character that follows it
either is a special character or should be interpreted literally. The following table
lists the escape characters:
Escaped
character
Description
\a
Pattern
Matches
\a
"\u0007"
"Warning!"
'\u0007'
in
+
338
VB.NET
\b
In a character class,
matches a backspace,
\u0008.
[\b]{3,}
"\b\b\b\b"
"\b\b\b\b"
\t
(\w+)\t
"Name\t", "Addr\t"
in "Name\tAddr\t"
\r
Matches
a
carriage
return, \u000D. (\r is
not equivalent to the
newline character, \n.)
\r\n(\w+)
"\r\nHello"
in
"\r\Hello\nWorld."
\v
[\v]{2,}
"\v\v\v" in "\v\v\v"
\f
[\f]{2,}
"\f\f\f" in "\f\f\f"
\n
Matches
\u000A.
\r\n(\w+)
"\r\nHello"
in
"\r\Hello\nWorld."
\e
Matches
\u001B.
\e
"\x001B" in
"\x001B"
\ nnn
Uses
octal
representation to specify
a
character
(nnn
consists of up to three
digits).
\w\040\w
\x nn
Uses
hexadecimal
representation to specify
a character (nn consists
of exactly two digits).
\w\x20\w
\c X\c x
Matches
the
ASCII
control character that is
specified by X or x,
where X or x is the letter
of the control character.
\cC
"\x0003" in
"\x0003" (Ctrl-C)
an
new
line,
escape,
in
339
VB.NET
\u nnnn
Matches
a
Unicode
character
by
using
hexadecimal
representation (exactly
four
digits,
as
represented by nnnn).
\w\u0020\w
When followed by a
character that is not
recognized
as
an
escaped
character,
matches that character.
\d+[\+x\*]\d+\d+[\+x\*\d+
Character Classes
A character class matches any one of a set of characters. The following table
describes the character classes:
Character class
Description
Pattern
Matches
[character_group]
Matches
any
single
character
in
character_group.
By
default, the match is
case-sensitive.
[mn]
"m" in "mat"
"m",
"n"
in
"moon"
[^character_group]
[^aei]
[ first - last ]
Character
range:
Matches
any
single
character in the range
from first to last.
(\w+)\t
"Name\t",
"Addr\t"
in
"Name\tAddr\t"
a.e
"ave" in "have"
"ate" in "mate"
340
VB.NET
\p{ name }
Matches
any
single
character in the Unicode
general
category
or
named block specified
by name.
\p{Lu}
\P{ name }
Matches
any
single
character that is not in
the
Unicode
general
category or named block
specified by name.
\P{Lu}
\w
Matches
character.
\w
\W
\W
"#" in "Room#1"
\s
\w\s
\S
\s\S
\d
Matches
digit.
\d
\D
\D
any
any
word
decimal
Anchors
Anchors allow a match to succeed or fail depending on the current position in the
string. The following table lists the anchors:
Assertion
Description
Pattern
Matches
^\d{3}
"567" in "567-777-"
341
VB.NET
-\d{4}$
"-2012"
2012"
\A
\A\w{3}
"Code"
007-"
in
"Code-
\Z
-\d{3}\Z
"-007" in
901-007"
"Bond-
\z
-\d{3}\z
"-333"
333"
"-901-
\G
\\G\(\d\)
\b
\w
\B
\Bend\w*\b
"ends", "ender" in
"end sends endure
lender"
in
in
"8-12-
Grouping Constructs
Grouping constructs delineate sub-expressions of a regular expression and
capture substrings of an input string. The following table lists the grouping
constructs:
Grouping
construct
Description
Pattern
Matches
(subexpression)
Captures
the
matched
subexpression
(\w)\1
"ee" in "deep"
342
VB.NET
and assigns it a
zero-based
ordinal number.
(?<
name
>subexpression)
Captures
the
matched
subexpression
into a named
group.
(?< double>\w)\k<
double>
"ee" in "deep"
(?<
name1
name2
>subexpression)
Defines a
balancing group
definition.
(((?'Open'\()[^\(\)]
*)+((?'CloseOpen'\))[^\(\)]*)+)
*(?(Open)(?!))$
"((1-3)*(31))"
in
"3+2^((13)*(3-1))"
(?:
subexpression)
Defines a
noncapturing
group.
Write(?:Line)?
"WriteLine" in
"Console.Write
Line()"
(?imnsximnsx:subexpres
sion)
Applies or
disables the
specified options
withinsubexpress
ion.
A\d{2}(?i:\w+)\b
"A12xl",
"A12XL"
in
"A12xl A12XL
a12xl"
(?=
subexpression)
Zero-width
positive
lookahead
assertion.
\w+(?=\.)
(?!
subexpression)
Zero-width
negative
lookahead
assertion.
\b(?!un)\w+\b
"sure", "used"
in "unsure
sure unity
used"
(?<
=subexpression)
Zero-width
positive
lookbehind
assertion.
(?< =19)\d{2}\b
"51", "03" in
"1851 1999
1950 1905
2003"
343
VB.NET
(?<
subexpression)
(?>
subexpression)
Zero-width
negative
lookbehind
assertion.
Nonbacktracking
(or "greedy")
subexpression.
(?< !19)\d{2}\b
"ends",
"ender" in
"end sends
endure lender"
[13579](?>A+B+)
"1ABB",
"3ABB",
and
"5AB"
in
"1ABB 3ABBC
5AB 5AC"
Quantifiers
Quantifiers specify how many instances of the previous element (which can be a
character, a group, or a character class) must be present in the input string for a
match to occur.
Quantifier
Description
Pattern
Matches
\d*\.\d
Matches
element
times.
"be+"
"rai?n"
"ran", "rain"
{n}
",\d{3}"
",043"
in
"1,043.6",
",876",
",543",
and
",210"
in
"9,876,543,210"
{ n ,}
"\d{2,}"
{n,m}
"\d{3,5}"
the previous
one or more
344
VB.NET
but no
times.
more
than
*?
\d*?\.\d
+?
"be+?"
??
"rai??n"
"ran", "rain"
{ n }?
",\d{3}?"
",043"
in
"1,043.6",
",876",
",543",
and
",210"
in
"9,876,543,210"
{ n ,}?
"\d{2,}?"
{ n , m }?
"\d{3,5}?"
Backreference Constructs
Backreference constructs allow a previously matched sub-expression to be
identified subsequently in the same regular expression. The following table lists
these constructs:
Backreference
construct
Description
Pattern
Matches
345
VB.NET
\ number
(\w)\1
"ee"
"seek"
in
Named
backreference.
Matches the value of a named
expression.
(?<
char>\w)\k<
char>
"ee"
"seek"
in
Alternation Constructs
Alternation constructs modify a regular expression to enable either/or matching.
The following table lists the alternation constructs:
Alternation
construct
Description
(?(
expression
)yes | no )
Matches yes if
expression
matches;
otherwise,
matches
the
optional no part.
Expression
is
interpreted as a
zero-width
assertion.
(?( name
)yes | no )
Matches yes if
the
named
capture
name
has a match;
otherwise,
matches
the
optional no.
Pattern
Matches
th(e|is|at)
"the",
"this" in
"this
is
the day. "
(?(A)A\d{2}\b|\b\d{3}\b)
"A10",
"910" in
"A10
C103
910"
(?<
quoted>")?(?(quoted).+?"|\S+\s)
Dogs.jpg,
"Yiska
playing.jp
g"
in
"Dogs.jpg
"Yiska
playing.jp
g""
346
VB.NET
Substitutions
Substitutions are used in replacement patterns. The following table lists the
substitutions:
Chara
cter
Description
Pattern
Replace
ment
pattern
Input
string
Result
string
$num
ber
Substitutes
the substring
matched by
group
number.
\b(\w+)(\s)(\w+)\b
$3$2$1
"one two"
"two one"
${na
me}
Substitutes
the substring
matched by
the
namedgroupn
ame.
\b(?<
word1>\w+)(\s)(?<
word2>\w+)\b
${word2}
${word1}
"one two"
"two one"
$$
Substitutes a
literal "$".
\b(\d+)\s?USD
$$$1
"103 USD"
"$103"
$&
Substitutes a
copy of the
whole match.
**$&
"$1.30"
"**$1.30**"
(\$*(\d*(\.+\d+)?)
{1})
$`
Substitutes all
the text of
the input
string before
the match.
B+
$`
"AABBCC"
"AAAACC"
$'
Substitutes all
the text of
the input
string after
the match.
B+
$'
"AABBCC"
"AACCCC"
B+(C+)
$+
"AABBCCDD"
AACCDD
$+
Substitutes
the last group
347
VB.NET
that was
captured.
Substitutes
the entire
input string.
$_
B+
$_
"AABBCC"
"AAAABBCC
CC"
Miscellaneous Constructs
Following are various miscellaneous constructs:
Construct
Definition
Example
(?imnsximnsx)
\bA(?i)b\w+\b
matches
"ABA", "Able" in "ABA Able
Act"
(?#comment)
In-line
comment.
The
comment ends at the first
closing parenthesis.
# [to
line]
X-mode
comment.
The
comment
starts
at
an
unescaped # and continues
to the end of the line.
(?x)\bA\w+\b#Matches
words starting with A
end
of
VB.NET
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
349
VB.NET
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
350
VB.NET
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
"
World
351
VB.NET
The data residing in a data store or database is retrieved through the data
provider. Various components of the data provider retrieve data for the
application and update data.
An application accesses data either through a dataset or a data reader.
Data readers provide data to the application in a read-only and forwardonly mode.
352
VB.NET
Data Provider
A data provider is used for connecting to a database, executing commands and
retrieving data, storing it in a dataset, reading the retrieved data and updating
the database.
The data provider in ADO.Net consists of the following four objects:
S.N
Connection
This component is used to set up a connection with a data source.
Command
A command is a SQL statement or a stored procedure used to retrieve,
insert, delete or modify data in a data source.
DataReader
Data reader is used to retrieve data from a data source in a read-only
and forward-only mode.
DataAdapter
This is integral to the working of ADO.Net since data is transferred to and
The .Net Framework data provider for SQL Server - provides access to
Microsoft SQL Server.
The .Net Framework data provider for OLE DB - provides access to data
sources exposed by using OLE DB.
The .Net Framework data provider for ODBC - provides access to data
sources exposed by ODBC.
The .Net Framework data provider for Oracle - provides access to Oracle
data source.
353
VB.NET
DataSet
DataSet is an in-memory representation of data. It is a disconnected, cached set
of records that are retrieved from a database. When a connection is established
with the database, the data adapter creates a dataset and stores data in it. After
the data is retrieved and stored in a dataset, the connection with the database is
closed. This is called the 'disconnected architecture'. The dataset works as a virtual
database containing tables, rows, and columns.
The following diagram shows the dataset object model:
The DataSet class is present in the System.Data namespace. The following table
describes all the components of DataSet:
S.N
DataTableCollection
It contains all the tables retrieved from the data source.
DataRelationCollection
It contains relationships and the links between tables in a data set.
354
VB.NET
ExtendedProperties
It contains additional information, like the SQL statement for retrieving
data, time of retrieval, etc.
DataTable
It represents a table in the DataTableCollection of a dataset. It consists
of the DataRow and DataColumn objects. The DataTable objects are casesensitive.
DataRelation
It represents a relationship in the DataRelationshipCollection of the
dataset. It is used to relate two DataTable objects to each other through
the DataColumn objects.
DataRowCollection
It contains all the rows in a DataTable.
DataView
It represents a fixed customized view of a DataTable for sorting, filtering,
searching, editing, and navigation.
PrimaryKey
It represents the column that uniquely identifies a row in a DataTable.
DataRow
It represents a row in the DataTable. The DataRow object and its
properties and methods are used to retrieve, evaluate, insert, delete, and
update values in the DataTable. The NewRow method is used to create a
new row and the Add method adds a row to the table.
10
DataColumnCollection
It represents all the columns in a DataTable.
11
DataColumn
It consists of the number of columns that comprise a DataTable.
Connecting to a Database
The .Net Framework provides two types of Connection classes:
SqlConnection - designed for connecting to Microsoft SQL Server.
355
VB.NET
Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a database
named testDB. Please consult 'SQL Server' tutorial for creating databases and
database tables in SQL Server.
Let us connect to this database. Take the following steps:
Select a server name and the database name in the Add Connection dialog
box.
356
VB.NET
VB.NET
358
VB.NET
359
VB.NET
360
VB.NET
Choose the database object, Customers table in our example, and click the
Finish button.
Select the Preview Data link to see the data in the Results grid:
361
VB.NET
When the application is run using Start button available at the Microsoft
Visual Studio tool bar, it will show the following window:
Example 2
In this example, let us access data in a DataGridView control using code. Take the
following steps:
Double click the button control to add the required code for the Click event
of the button, as shown below:
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
'TODO: This line of code loads data into the
'TestDBDataSet.CUSTOMERS' table.
You can move, or remove it, as
needed.
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
' Set the caption bar text of the form.
Me.Text = "tutorialspoint.com"
End Sub
362
VB.NET
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:
Clicking the Fill button displays the table on the data grid view control:
363
VB.NET
Example 3
So far, we have used tables and databases already existing in our computer. In
this example, we will create a table, add columns, rows, and data into it and
display the table using a DataGridView object.
Take the following steps:
VB.NET
VB.NET
table.Rows.Add(newrow)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim ds As New DataSet
ds = CreateDataSet()
DataGridView1.DataSource = ds.Tables("Student")
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:
Clicking the Fill button displays the table on the data grid view control:
366
VB.NET
VB.Net provides support for interoperability between the COM object model of
Microsoft Excel 2010 and your application.
To avail this interoperability in your application, you need to import the namespace
Microsoft.Office.Interop.Excel in your Windows Form Application.
367
VB.NET
On the COM tab, locate Microsoft Excel Object Library and then click Select.
Click OK.
Double click the code window and populate the Click event of Button1, as
shown below.
'
VB.NET
VB.NET
Clicking on the Button would display the following excel sheet. You will be asked
to save the workbook.
370
VB.NET
371
VB.NET
VB.Net
allows
sending
e-mails
from
your
application.
The System.Net.Mail namespace contains classes used for sending e-mails to a
Simple Mail Transfer Protocol (SMTP) server for delivery.
The following table lists some of these commonly used classes:
S.N
Class
Description
Attachment
AttachmentCollection
MailAddress
MailAddressCollection
MailMessage
SmtpClient
SmtpException
372
VB.NET
S.N
Property
Description
ClientCertificates
Credentials
EnableSsl
Host
Port
Gets or sets
transactions.
Timeout
UseDefaultCredentials
the
port
used
used
for
to
SMTP
Dispose
Sends a QUIT message to the SMTP server, gracefully ends the TCP
connection, and releases all resources used by the current instance of the
SmtpClient class.
Dispose(Boolean)
Sends a QUIT message to the SMTP server, gracefully ends the TCP
connection, releases all resources used by the current instance of the
SmtpClient class, and optionally disposes of the managed resources.
373
VB.NET
OnSendCompleted
Raises the SendCompleted event.
Send(MailMessage)
Sends the specified message to an SMTP server for delivery.
SendAsync(MailMessage, Object)
Sends the specified e-mail message to an SMTP server for delivery. This
method does not block the calling thread and allows the caller to pass an
object to the method that is invoked when the operation completes.
SendAsyncCancel
Cancels an asynchronous operation to send an e-mail message.
SendMailAsync(MailMessage)
Sends the specified message to an SMTP server for delivery as an
asynchronous operation.
10
11
ToString
Returns a string that represents the current object.
374
VB.NET
The following example demonstrates how to send mail using the SmtpClient class.
Following points are to be noted in this respect:
You must specify the SMTP host server that you use to send e-mail.
The Host and Port properties will be different for different host server. We
will be using gmail server.
You need to give the Credentials for authentication, if required by the SMTP
server.
You should also provide the email address of the sender and the e-mail
address
or
addresses
of
the
recipients
using
the MailMessage.From and MailMessage.Toproperties, respectively.
You
should
also
specify
the MailMessage.Bodyproperty.
the
message
content
using
Example
In this example, let us create a simple application that would send an e-mail. 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 - 'From', 'To:' and 'Message:'
respectively.
Change the name properties of the texts to txtFrom, txtTo and txtMessage
respectively.
Imports System.Net.Mail
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 = "tutorialspoint.com"
End Sub
VB.NET
End Sub
You must provide your gmail address and real password for credentials.
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, which
you will use to send your e-mails, try it yourself.
376
VB.NET
377
VB.NET
The Extensible Markup Language (XML) is a markup language much like HTML or
SGML. This is recommended by the World Wide Web Consortium and available as
an open standard.
The System.Xml namespace in the .Net Framework contains classes for
processing XML documents. Following are some of the commonly used classes in
the System.Xml namespace.
S.N
Class
Description
XmlAttribute
XmlCDataSection
XmlCharacterData
XmlComment
Represents
comment.
XmlConvert
XmlDeclaration
XmlDictionary
the
content
of
an
XML
378
VB.NET
XmlDictionaryReader
XmlDictionaryWriter
10
XmlDocument
11
XmlDocumentFragment
12
XmlDocumentType
Represents
declaration.
13
XmlElement
Represents an element.
14
XmlEntity
15
XmlEntityReference
16
XmlException
17
XmlImplementation
18
XmlLinkedNode
19
XmlNode
20
XmlNodeList
the
document
for
type
set
of
379
VB.NET
21
XmlNodeReader
22
XmlNotation
23
XmlParserContext
24
XmlProcessingInstruction
25
XmlQualifiedName
26
XmlReader
27
XmlReaderSettings
28
XmlResolver
29
XmlSecureResolver
30
XmlSignificantWhitespace
31
XmlText
380
VB.NET
32
XmlTextReader
33
XmlTextWriter
34
XmlUrlResolver
35
XmlWhitespace
Represents
content.
36
XmlWriter
37
XmlWriterSettings
white
space
in
element
Simple API for XML (SAX): Here, you register callbacks for events of
interest and then let the parser proceed through the document. This is
useful when your documents are large or you have memory limitations, it
parses the file as it reads it from disk, and the entire file is never stored in
memory.
Document Object Model (DOM) API: This is World Wide Web Consortium
recommendation wherein the entire file is read into memory and stored in
a hierarchical (tree-based) form to represent all the features of an XML
document.
381
VB.NET
SAX obviously can't process information as fast as DOM can when working with
large files. On the other hand, using DOM exclusively can really kill your resources,
especially if used on a lot of small files.
SAX is read-only, while DOM allows changes to the XML file. Since these two
different APIs literally complement each other there is no reason why you can't
use them both for large projects.
For all our XML code examples, let's use a simple XML file movies.xml as an input:
<?xml version="1.0"?>
VB.NET
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>
Example 1
This example demonstrates reading XML data from the file movies.xml.
Take the following steps:
Add a label in the form and change its text to 'Movies Galore'.
Add three list boxes and three buttons to show the title, type and
description of a movie from the xml file.
Imports System.Xml
Public Class Form1
383
VB.NET
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
ListBox1().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "movie"
Then
ListBox1.Items.Add(xr.GetAttribute(0))
End If
Loop
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles
Button2.Click
ListBox2().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name = "type"
Then
ListBox2.Items.Add(xr.ReadElementString)
Else
xr.Read()
End If
Loop
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles
Button3.Click
ListBox3().Items.Clear()
Dim xr As XmlReader = XmlReader.Create("movies.xml")
Do While xr.Read()
If xr.NodeType = XmlNodeType.Element AndAlso xr.Name =
"description" Then
ListBox3.Items.Add(xr.ReadElementString)
Else
xr.Read()
End If
384
VB.NET
Loop
End Sub
End Class
Execute and run the above code using Start button available at the Microsoft
Visual Studio tool bar. Clicking on the buttons would display, title, type and
description of the movies from the file.
The XmlWriter class is used to write XML data into a stream, a file, or a
TextWriter object. It also works in a forward-only, non-cached manner.
Example 2
Let us create an XML file by adding some data at runtime. Take the following
steps:
Imports System.Xml
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 = "tutorialspoint.com"
End Sub
385
VB.NET
VB.NET
xw.WriteEndDocument()
xw.Flush()
xw.Close()
WebBrowser1.Url = New Uri(AppDomain.CurrentDomain.BaseDirectory +
"authors.xml")
End Sub
End Class
Execute and run the above code using Start button available at the
Microsoft Visual Studio tool bar. Clicking on the Show Author File would
display the newly created authors.xml file on the web browser.
387
VB.NET
AppendChild
Adds the specified node to the end of the list of child nodes, of this node.
CreateAttribute(String)
Creates an XmlAttribute with the specified Name.
CreateComment
Creates an XmlComment containing the specified data.
CreateDefaultAttribute
Creates a default attribute with the specified prefix, local name and
namespace URI.
CreateElement(String)
Creates an element with the specified name.
CreateProcessingInstruction
Creates an XmlProcessingInstruction with the specified name and data.
10
CreateSignificantWhitespace
Creates an XmlSignificantWhitespace node.
11
CreateTextNode
Creates an XmlText with the specified text.
12
CreateWhitespace
Creates an XmlWhitespace node.
388
VB.NET
13
CreateXmlDeclaration
Creates an XmlDeclaration node with the specified values.
14
GetElementById
Gets the XmlElement with the specified ID.
15
GetElementsByTagName(String)
Returns an XmlNodeList containing a list of all descendant elements that
match the specified Name.
16
GetElementsByTagName(String, String)
Returns an XmlNodeList containing a list of all descendant elements that
match the specified LocalName and NamespaceURI.
17
InsertAfter
Inserts the specified node immediately after the specified reference node.
18
InsertBefore
Inserts the specified node immediately before the specified reference
node.
19
Load(Stream)
Loads the XML document from the specified stream.
20
Load(String)
Loads the XML document from the specified URL.
21
Load(TextReader)
Loads the XML document from the specified TextReader.
22
Load(XmlReader)
Loads the XML document from the specified XmlReader.
23
LoadXml
Loads the XML document from the specified string.
24
PrependChild
Adds the specified node to the beginning of the list of child nodes for this
node.
389
VB.NET
25
ReadNode
Creates an XmlNode object based on the information in the XmlReader.
The reader must be positioned on a node or attribute.
26
RemoveAll
Removes all the child nodes and/or attributes of the current node.
27
RemoveChild
Removes specified child node.
28
ReplaceChild
Replaces the child node oldChild with newChild node.
29
Save(Stream)
Saves the XML document to the specified stream.
30
Save(String)
Saves the XML document to the specified file.
31
Save(TextWriter)
Saves the XML document to the specified TextWriter.
32
Save(XmlWriter)
Saves the XML document to the specified XmlWriter.
Example 3
In this example, let us insert some new nodes in the xml document authors.xml
and then show all the authors' first names in a list box.
Take the following steps:
Add the authors.xml file in the bin/Debug folder of your application (it
should be there if you have tried the last example)
Add a list box and a button control in the form and set the text property of
the button control to Show Authors.
Imports System.Xml
390
VB.NET
Execute and run the above code using Start button available at the
Microsoft Visual Studio tool bar. Clicking on the Show Author button would
display the first names of all the authors including the one we have added
at runtime.
391
VB.NET
392
VB.NET
A dynamic web application consists of either or both of the following two types of
programs:
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:
C#
Jscript
J#
Description
Application
VB.NET
Response
Server
Session
394
VB.NET
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.
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 consist 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:
395
VB.NET
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:
396
VB.NET
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
To add controls on the web page, go to the design view. Add three labels,
a text box and a button on the form.
397
VB.NET
Double-click the button and add the following code to the Click event of the
button:
398
VB.NET
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 a 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.
399
VB.NET
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:
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.
Select New Web Site to open the New Web Site dialog box.
VB.NET
Provide a name and location for the WCF Service and click OK.
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.
Replace the code of the IService.vb file with the given code:
<OperationContract()>
Function GetName(ByVal symbol As String) As String
End Interface
VB.NET
' 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
VB.NET
Dim i As Integer
For i = 0 To i = stocks.GetLength(0) - 1
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.
403
VB.NET
The following diagram displays the result of testing the GetPrice operation:
The following diagram displays the result of testing the GetName operation:
404
VB.NET
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.
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.
405
VB.NET
Creates the Address and Binding for the service in the web.config file.
Double click the Get Price button in the form, to enter the following code
snippet on its Click event:
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:
406
VB.NET
Enter a symbol and click the Get Price button to get the hard-coded price:
407