CSC 215 Notes_3
CSC 215 Notes_3
VB.Net - Overview
Visual Basic .NET (VB.NET) is an object-oriented computer programming language implemented on
the .NET Framework. Although it is an evolution of classic Visual Basic language, it is not
backwards-compatible with VB6, and any code written in the old version does not compile under
VB.NET.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts.
Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long, String,
Boolean, etc.) and user-defined types, events, and even assemblies. All objects inherits from the
base class Object.
VB.NET is implemented by Microsoft's .NET framework. Therefore, it has full access to all the
libraries in the .Net Framework. It's also possible to run VB.NET programs on Mono, the open-
source alternative to .NET, not only under Windows, but even Linux or Mac OSX.
Object oriented.
Component oriented.
Easy to learn.
Structured language.
It produces efficient programs.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 1/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Boolean Conditions
Assembly Versioning
Properties and Events
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
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
The .Net framework applications are multi-platform applications. The framework has been designed
in such a way that it can be used from any of the following languages: Visual Basic, C#, C++,
Jscript, and COBOL, etc.
All these languages can access the framework as well as communicate with each other.
The .Net framework consists of an enormous library of codes used by the client languages like
VB.Net. These languages use object-oriented methodology.
Windows Forms
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 3/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Framework which includes a Visual Basic compiler and runs on several operating systems, including
various flavors of Linux and Mac OS. The most recent version is VB 2012.
The stated purpose of Mono is not only to be able to run Microsoft .NET applications cross-platform,
but also to bring better development tools to Linux developers. Mono can be run on many operating
systems including Android, BSD, iOS, Linux, OS X, Windows, Solaris and UNIX.
Namespace declaration
A class or module
Comments
Let us look at a simple code that would print the words "Hello World" −
Live Demo
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!
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 4/188
7/21/22, 1:32 PM VB.Net - Quick Guide
The first line of the program Imports System is used to include the System namespace in the
program.
The next line has a Module declaration, the module Module1. VB.Net is completely object
oriented, so every program must contain a module of a class that contains the data and
procedures that your program uses.
Classes or Modules generally would contain more than one procedure. Procedures contain the
executable code, or in other words, they define the behavior of the class. A procedure could be
any of the following −
Function
Sub
Operator
Get
Set
AddHandler
RemoveHandler
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 5/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
When we consider a VB.Net program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods and
instance variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors - wagging, barking, eating, etc. An object is an instance of a class.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 6/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Class − A class can be defined as a template/blueprint that describes the behaviors/states that
objects of its type support.
Instance Variables − Each object has its unique set of instance variables. An object's state is
created by the values assigned to these instance variables.
Let us look at an implementation of a Rectangle class and discuss VB.Net basic syntax on the basis
of our observations in it −
Live Demo
Imports System
Public Class Rectangle
Private length As Double
Private width As Double
'Public methods
Public Sub AcceptDetails()
length = 4.5
width = 3.5
End Sub
End Sub
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 7/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Console.ReadLine()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Length: 4.5
Width: 3.5
Area: 15.75
In previous chapter, we created a Visual Basic module that held the code. Sub Main indicates the
entry point of VB.Net program. Here, we are using Class that contains both code and data. You use
classes to create objects. For example, in the code, r is a Rectangle object.
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 −
Identifiers
An identifier is a name used to identify a class, variable, function, or any other user-defined item.
The basic rules for naming classes in VB.Net are as follows −
A name must begin with a letter that could be followed by a sequence of letters, digits (0 - 9) or
underscore. The first character in an identifier cannot be a digit.
It must not contain any embedded space or symbol like ? - +! @ # % ^ & * ( ) [ ] { } . ; : " ' / and
\. However, an underscore ( _ ) can be used.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 8/188
7/21/22, 1:32 PM VB.Net - Quick Guide
VB.Net Keywords
The following table lists the VB.Net reserved keywords −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 9/188
7/21/22, 1:32 PM VB.Net - Quick Guide
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 10/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Double 8 bytes
-1.79769313486231570E+308 through
-4.94065645841246544E-324, for negative values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive values
8 bytes on 64-bit
platform
Single 4 bytes
-3.4028235E+38 through -1.401298E-45 for negative values;
implementing
platform
User-Defined Depends on Each member of the structure has a range determined by its data
implementing type and independent of the ranges of the other members
platform
Example
The following example demonstrates use of some of the types −
Live Demo
Module DataTypes
Sub Main()
Dim b As Byte
Dim n As Integer
Dim si As Single
Dim d As Double
Dim da As Date
Dim c As Char
Dim s As String
Dim bl As Boolean
b = 1
n = 1234567
si = 0.12345678901234566
d = 0.12345678901234566
da = Today
c = "U"c
s = "Me"
If bl Then
'the oath taking
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 12/188
7/21/22, 1:32 PM VB.Net - Quick Guide
the oath taking
Console.Write(c & " and," & s & vbCrLf)
Console.WriteLine("declaring on the day of: {0}", da)
Console.WriteLine("We will learn VB.Net seriously")
Console.WriteLine("Lets see what happens to the floating point variables:")
Console.WriteLine("The Single: {0}, The Double: {1}", si, d)
End If
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
U and, Me
declaring on the day of: 12/4/2012 12:00:00 PM
We will learn VB.Net seriously
Lets see what happens to the floating point variables:
The Single:0.1234568, The Double: 0.123456789012346
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 13/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
CBool(expression)
2
CByte(expression)
3
CChar(expression)
4
CDate(expression)
5
CDbl(expression)
6
CDec(expression)
7
CInt(expression)
8
CLng(expression)
9
CObj(expression)
10
CSByte(expression)
11
CShort(expression)
12
CSng(expression)
13
CStr(expression)
14
CUInt(expression)
15
CULng(expression)
16
CUShort(expression)
Example
The following example demonstrates some of these functions −
Live Demo
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))
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 15/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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
VB.Net - Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in VB.Net has a specific type, which determines the size and layout of the variable's
memory; the range of values that can be stored within that memory; and the set of operations that
can be applied to the variable.
We have already discussed various data types. The basic value types provided in VB.Net can be
categorized as −
Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char
VB.Net also allows defining other value types of variable like Enum and reference types of variables
like Class. We will discuss date types and Classes in subsequent chapters.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 16/188
7/21/22, 1:32 PM VB.Net - Quick Guide
The Dim statement is used for variable declaration and storage allocation for one or more variables.
The Dim statement is used at module, class, structure, procedure or block level.
Where,
accessmodifier defines the access levels of the variables, it has values as - Public, Protected,
Friend, Protected Friend and Private. Optional.
Shared declares a shared variable, which is not associated with any specific instance of a
class or structure, rather available to all the instances of the class or structure. Optional.
Shadows indicate that the variable re-declares and hides an identically named element, or set
of overloaded elements, in a base class. Optional.
Static indicates that the variable will retain its value, even when the after termination of the
procedure in which it is declared. Optional.
ReadOnly means the variable can be read, but not written. Optional.
WithEvents specifies that the variable is used to respond to events raised by the instance
assigned to the variable. Optional.
Variablelist provides the list of variables declared.
Each variable in the variable list has the following syntax and parts −
Where,
datatype − Required if Option Strict is On. It specifies the data type of the variable.
initializer − Optional if New is not specified. Expression that is evaluated and assigned to the
variable when it is created.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 17/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Some valid variable declarations along with their definition are shown here −
variable_name = value;
for example,
Dim pi As Double
pi = 3.14159
Example
Try the following example which makes use of various types of variables −
Live Demo
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)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 18/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
Live Demo
Module variablesNdataypes
Sub Main()
Dim message As String
Console.Write("Enter message: ")
message = Console.ReadLine
Console.WriteLine()
Console.WriteLine("Your Message: {0}", message)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result (assume the user
inputs Hello World) −
lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of
an assignment.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 19/188
7/21/22, 1:32 PM VB.Net - Quick Guide
rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an
assignment.
Variables are lvalues and so may appear on the left-hand side of an assignment. Numeric literals
are rvalues and so may not be assigned and can not appear on the left-hand side. Following is a
valid statement −
Dim g As Integer = 20
But following is not a valid statement and would generate compile-time error −
20 = g
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.
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.
Where,
attributelist − specifies the list of attributes applied to the constants; you can provide multiple
attributes separated by commas. Optional.
accessmodifier − specifies which code can access these constants. Optional. Values can be
either of the: Public, Protected, Friend, Protected Friend, or Private.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 20/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Shadows − this makes the constant hide a programming element of identical name in a base
class. Optional.
Constantlist − gives the list of names of constants declared. Required.
Where, each constant name has the following syntax and parts −
For example,
Example
The following example demonstrates declaration and use of a constant value −
Live Demo
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
1
vbCrLf
2
vbCr
3
vbLf
Linefeed character.
4
vbNewLine
Newline character.
5
vbNullChar
Null character.
6
vbNullString
Not the same as a zero-length string (""); used for calling external procedures.
7
vbObjectError
Error number. User-defined error numbers should be greater than this value. For
example: Err.Raise(Number) = vbObjectError + 1000
8
vbTab
Tab character.
9
vbBack
Backspace character.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 22/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
Where,
accessmodifier − specifies which code can access these enumerations. Optional. Values can
be either of the: Public, Protected, Friend or Private.
Shadows − this makes the enumeration hide a programming element of identical name in a
base class. Optional.
enumerationname − name of the enumeration. Required
datatype − specifies the data type of the enumeration and all its members.
memberlist − specifies the list of member constants being declared in this statement.
Required.
Each member in the memberlist has the following syntax and parts:
Where,
For example,
Enum Colors
red = 1
orange = 2
yellow = 3
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 23/188
7/21/22, 1:32 PM VB.Net - Quick Guide
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Example
The following example demonstrates declaration and use of the Enum variable Colors −
Live Demo
Module constantsNenum
Enum Colors
red = 1
orange = 2
yellow = 3
green = 4
azure = 5
blue = 6
violet = 7
End Enum
Sub Main()
Console.WriteLine("The Color Red is : " & Colors.red)
Console.WriteLine("The Color Yellow is : " & Colors.yellow)
Console.WriteLine("The Color Blue is : " & Colors.blue)
Console.WriteLine("The Color Green is : " & Colors.green)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
VB.Net - Modifiers
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 24/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 25/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1 Ansi Specifies that Visual Basic should marshal all strings to American
National Standards Institute (ANSI) values regardless of the name of
the external procedure being declared.
Declare Statement
Function Statement
Sub Statement
6 ByVal Specifies that an argument is passed in such a way that the called
procedure or property cannot change the value of a variable
underlying the argument in the calling code. It is used under the
contexts of −
Declare Statement
Function Statement
Operator Statement
Property Statement
Sub Statement
8 Friend
Specifies that one or more declared programming elements are
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 26/188
7/21/22, 1:32 PM VB.Net - Quick Guide
11 Key The Key keyword enables you to specify behavior for properties of
anonymous types.
13 MustInherit Specifies that a class can be used only as a base class and that you
cannot create an object directly from it.
19 Out For generic type parameters, the Out keyword specifies that the type
is covariant.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 27/188
7/21/22, 1:32 PM VB.Net - Quick Guide
28 ReadOnly Specifies that a variable or property can be read but not written.
31 Static Specifies that one or more declared local variables are to continue to
exist and retain their latest values after termination of the procedure
in which they are declared.
32 Unicode Specifies that Visual Basic should marshal all strings to Unicode
values regardless of the name of the external procedure being
declared.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 28/188
7/21/22, 1:32 PM VB.Net - Quick Guide
VB.Net - Statements
A statement is a complete instruction in Visual Basic programs. It may contain keywords, operators,
variables, literal values, constants and expressions.
Declaration statements − these are the statements where you name a variable, constant, or
procedure, and can also specify a data type.
Executable statements − these are the statements, which initiate actions. These statements
can call a method or function, loop or branch through blocks of code or assign values or
expression to a variable or constant. In the last case, it is called an Assignment statement.
Declaration Statements
The declaration statements are used to name and define procedures, variables, properties, arrays,
and constants. When you declare a programming element, you can also define its data type, access
level, and scope.
The programming elements you may declare include variables, constants, enumerations, classes,
structures, modules, interfaces, procedures, procedure parameters, function returns, external
procedure references, operators, properties, events, and delegates.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 29/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Dim Statement Dim number As Integer
Dim quantity As Integer = 100
Declares and allocates storage
Dim message As String = "Hello!"
space for one or more variables.
2
Const Statement Const maximum As Long = 1000
Const naturalLogBase As Object
Declares and defines one or more
= CDec(2.7182818284)
constants.
3
Enum Statement Enum CoffeeMugSize
Jumbo
Declares an enumeration and defines
ExtraLarge
the values of its members. Large
Medium
Small
End Enum
4
Class Statement Class Box
Public length As Double
Declares the name of a class and
Public breadth As Double
introduces the definition of the Public height As Double
variables, properties, events, and End Class
procedures that the class comprises.
5
Structure Statement Structure Box
Public length As Double
Declares the name of a structure and
Public breadth As Double
introduces the definition of the Public height As Double
variables, properties, events, and End Structure
procedures that the structure
comprises.
6
Module Statement Public Module myModule
Sub Main()
Declares the name of a module and
Dim user As String =
introduces the definition of the
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 30/188
7/21/22, 1:32 PM VB.Net - Quick Guide
7
Interface Statement Public Interface MyInterface
Sub doSomething()
Declares the name of an interface
End Interface
and introduces the definitions of the
members that the interface
comprises.
8
Function Statement Function myFunction
(ByVal n As Integer) As Double
Declares the name, parameters, and
Return 5.87 * n
code that define a Function End Function
procedure.
9
Sub Statement Sub mySub(ByVal s As String)
Return
Declares the name, parameters, and
End Sub
code that define a Sub procedure.
10
Declare Statement Declare Function getUserName
Lib "advapi32.dll"
Declares a reference to a procedure
Alias "GetUserNameA"
implemented in an external file. (
ByVal lpBuffer As String,
ByRef nSize As Integer) As Integer
11
Operator Statement Public Shared Operator +
(ByVal x As obj, ByVal y As obj) As obj
Declares the operator symbol,
Dim r As New obj
operands, and code that define an ' implemention code for r = x + y
operator procedure on a class or Return r
structure. End Operator
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 31/188
7/21/22, 1:32 PM VB.Net - Quick Guide
13
Event Statement Public Event Finished()
14
Delegate Statement Delegate Function MathOperator(
ByVal x As Double,
Used to declare a delegate.
ByVal y As Double
) As Double
Executable Statements
An executable statement performs an action. Statements calling a procedure, branching to another
place in the code, looping through several statements, or evaluating an expression are executable
statements. An assignment statement is a special case of an executable statement.
Example
Live Demo
Module decisions
Sub Main()
'local variable definition '
Dim a As Integer = 10
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 32/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
VB.Net - Directives
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.
Where,
For example,
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 33/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Example
Live Demo
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 −
This directive allows including external code from an external code file into a source code file.
The parameters of #ExternalSource directive are the path of external file, line number of the first
line, and the line where the error occurred.
Example
Module mydirectives
Public Class ExternalSourceTester
Sub TestExternalSource()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 34/188
7/21/22, 1:32 PM VB.Net - Quick Guide
#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 −
For example,
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 35/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Example
Live Demo
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 −
#Region "identifier_string"
#End Region
For example,
#Region "StatsFunctions"
' Insert code for the Statistical functions here.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 36/188
7/21/22, 1:32 PM VB.Net - Quick Guide
#End Region
VB.Net - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. VB.Net is rich in built-in operators and provides following types of commonly used
operators −
Arithmetic Operators
Comparison Operators
Logical/Bitwise Operators
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 −
Show Examples
/ Divides one operand by another and returns a floating B / A will give 3.5
point result
MOD Modulus Operator and remainder of after an integer B MOD A will give 1
division
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 37/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Comparison Operators
Following table shows all the comparison operators supported by VB.Net. Assume variable A holds
10 and variable B holds 20, then −
Show Examples
= Checks if the values of two operands are equal or not; if (A = B) is not true.
yes, then condition becomes true.
<> Checks if the values of two operands are equal or not; if (A <> B) is true.
values are not equal, then condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand; if yes, then condition becomes
true.
< Checks if the value of left operand is less than the value (A < B) is true.
of right operand; if yes, then condition becomes true.
>= Checks if the value of left operand is greater than or (A >= B) is not true.
equal to the value of right operand; if yes, then
condition becomes true.
<= Checks if the value of left operand is less than or equal (A <= B) is true.
to the value of right operand; if yes, then condition
becomes true.
Apart from the above, VB.Net provides three more comparison operators, which we will be using in
forthcoming chapters; however, we give a brief description here.
Is Operator − It compares two object reference variables and determines if two object
references refer to the same object without performing value comparisons. If object1 and
object2 both refer to the exact same object instance, result is True; otherwise, result is False.
IsNot Operator − It also compares two object reference variables and determines if two object
references refer to different objects. If object1 and object2 both refer to the exact same object
instance, result is False; otherwise, result is True.
Like Operator − It compares a string against a pattern.
Logical/Bitwise Operators
Following table shows all the logical operators supported by VB.Net. Assume variable A holds
Boolean value True and variable B holds Boolean value False, then −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 38/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Show Examples
And It is the logical as well as bitwise AND operator. If both (A And B) is False.
the operands are true, then condition becomes true.
This operator does not perform short-circuiting, i.e., it
evaluates both the expressions.
Not It is the logical as well as bitwise NOT operator. Use to Not(A And B) is True.
reverses the logical state of its operand. If a condition is
true, then Logical NOT operator will make false.
AndAlso It is the logical AND operator. It works only on Boolean (A AndAlso B) is False.
data. It performs short-circuiting.
Bitwise operators work on bits and perform bit-by-bit operations. The truth tables for &, |, and ^ are
as follows −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 39/188
7/21/22, 1:32 PM VB.Net - Quick Guide
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
We have seen that the Bitwise operators supported by VB.Net are And, Or, Xor and Not. The Bit
shift operators are >> and << for left shift and right shift, respectively.
Assume that the variable A holds 60 and variable B holds 13, then −
Show Examples
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 40/188
7/21/22, 1:32 PM VB.Net - Quick Guide
And Bitwise AND Operator copies a bit to the result if it (A AND B) will give 12, which is
exists in both operands. 0000 1100
Or Binary OR Operator copies a bit if it exists in either (A Or B) will give 61, which is
operand. 0011 1101
Xor Binary XOR Operator copies the bit if it is set in one (A Xor B) will give 49, which is
operand but not both. 0011 0001
Not Binary Ones Complement Operator is unary and has (Not A ) will give -61, which is
the effect of 'flipping' bits. 1100 0011 in 2's complement
form due to a signed binary
number.
<< Binary Left Shift Operator. The left operands value is A << 2 will give 240, which is
moved left by the number of bits specified by the right 1111 0000
operand.
>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15, which is 0000
moved right by the number of bits specified by the right 1111
operand.
Assignment Operators
There are following assignment operators supported by VB.Net −
Show Examples
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 41/188
7/21/22, 1:32 PM VB.Net - Quick Guide
= Simple assignment operator, Assigns values from right C = A + B will assign value of A +
side operands to left side operand B into C
Miscellaneous Operators
There are few other important operators supported by VB.Net.
Show Examples
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 42/188
7/21/22, 1:32 PM VB.Net - Quick Guide
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 43/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Show Examples
Operator Precedence
Await Highest
Exponentiation (^)
All comparison operators (=, <>, <, <=, >, >=, Is, IsNot, Like,
TypeOf...Is)
Negation (Not)
Following is the general form of a typical decision making structure found in most of the
programming languages −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 44/188
7/21/22, 1:32 PM VB.Net - Quick Guide
VB.Net provides the following types of decision making statements. Click the following links to check
their details.
Statement Description
Select Case statement A Select Case statement allows a variable to be tested for
equality against a list of values.
nested Select Case You can use one select case statement inside another select
statements case statement(s).
VB.Net - Loops
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 45/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 46/188
7/21/22, 1:32 PM VB.Net - Quick Guide
For Each...Next 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.
Nested loops You can use one or more loops inside any another While, For or Do
loop.
VB.Net provides the following control statements. Click the following links to check their details.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 47/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Exit statement Terminates the loop or select case statement and transfers
execution to the statement immediately following the loop or select
case.
Continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
GoTo statement Transfers control to the labeled statement. Though it is not advised
to use GoTo statement in your program.
VB.Net - Strings
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.
Live Demo
Module strings
Sub Main()
Dim fname, lname, fullname, greetings As String
fname = "Rowan"
lname = "Atkinson"
fullname = fname + " " + lname
Console.WriteLine("Full Name: {0}", fullname)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 48/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
1
Chars
Gets the Char object at a specified position in the current String object.
2
Length
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 49/188
7/21/22, 1:32 PM VB.Net - Quick Guide
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 50/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Public Shared Function Compare ( strA As String, strB As String ) As Integer
Compares two specified string objects and returns an integer that indicates their relative
position in the sort order.
2
Public Shared Function Compare ( strA As String, strB As String, ignoreCase As
Boolean ) As Integer
Compares two specified string objects and returns an integer that indicates their relative
position in the sort order. However, it ignores case if the Boolean parameter is true.
3
Public Shared Function Concat ( str0 As String, str1 As String ) As String
4
Public Shared Function Concat ( str0 As String, str1 As String, str2 As String ) As
String
5
Public Shared Function Concat (str0 As String, str1 As String, str2 As String, str3
As String ) As String
6
Public Function Contains ( value As String ) As Boolean
Returns a value indicating whether the specified string object occurs within this string.
7
Public Shared Function Copy ( str As String ) As String
Creates a new String object with the same value as the specified string.
8
pPublic Sub CopyTo ( sourceIndex As Integer, destination As Char(),
destinationIndex As Integer, count As Integer )
Copies a specified number of characters from a specified position of the string object to a
specified position in an array of Unicode characters.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 51/188
7/21/22, 1:32 PM VB.Net - Quick Guide
9
Public Function EndsWith ( value As String ) As Boolean
Determines whether the end of the string object matches the specified string.
10
Public Function Equals ( value As String ) As Boolean
Determines whether the current string object and the specified string object have the
same value.
11
Public Shared Function Equals ( a As String, b As String ) As Boolean
Determines whether two specified string objects have the same value.
12
Public Shared Function Format ( format As String, arg0 As Object ) As String
Replaces one or more format items in a specified string with the string representation of a
specified object.
13
Public Function IndexOf ( value As Char ) As Integer
Returns the zero-based index of the first occurrence of the specified Unicode character in
the current string.
14
Public Function IndexOf ( value As String ) As Integer
Returns the zero-based index of the first occurrence of the specified string in this
instance.
15
Public Function IndexOf ( value As Char, startIndex As Integer ) As Integer
Returns the zero-based index of the first occurrence of the specified Unicode character in
this string, starting search at the specified character position.
16
Public Function IndexOf ( value As String, startIndex As Integer ) As Integer
Returns the zero-based index of the first occurrence of the specified string in this
instance, starting search at the specified character position.
17
Public Function IndexOfAny ( anyOf As Char() ) As Integer
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 52/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Returns the zero-based index of the first occurrence in this instance of any character in a
specified array of Unicode characters.
18
Public Function IndexOfAny ( anyOf As Char(), startIndex As Integer ) As Integer
Returns the zero-based index of the first occurrence in this instance of any character in a
specified array of Unicode characters, starting search at the specified character position.
19
Public Function Insert ( startIndex As Integer, value As String ) As String
Returns a new string in which a specified string is inserted at a specified index position in
the current string object.
20
Public Shared Function IsNullOrEmpty ( value As String ) As Boolean
21
Public Shared Function Join ( separator As String, ParamArray value As String() )
As String
Concatenates all the elements of a string array, using the specified separator between
each element.
22
Public Shared Function Join ( separator As String, value As String(), startIndex As
Integer, count As Integer ) As String
Concatenates the specified elements of a string array, using the specified separator
between each element.
23
Public Function LastIndexOf ( value As Char ) As Integer
Returns the zero-based index position of the last occurrence of the specified Unicode
character within the current string object.
24
Public Function LastIndexOf ( value As String ) As Integer
Returns the zero-based index position of the last occurrence of a specified string within
the current string object.
25
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 53/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Removes all the characters in the current instance, beginning at a specified position and
continuing through the last position, and returns the string.
26
Public Function Remove ( startIndex As Integer, count As Integer ) As String
Removes the specified number of characters in the current string beginning at a specified
position and returns the string.
27
Public Function Replace ( oldChar As Char, newChar As Char ) As String
Replaces all occurrences of a specified Unicode character in the current string object with
the specified Unicode character and returns the new string.
28
Public Function Replace ( oldValue As String, newValue As String ) As String
Replaces all occurrences of a specified string in the current string object with the
specified string and returns the new string.
29
Public Function Split ( ParamArray separator As Char() ) As String()
Returns a string array that contains the substrings in the current string object, delimited
by elements of a specified Unicode character array.
30
Public Function Split ( separator As Char(), count As Integer ) As String()
Returns a string array that contains the substrings in the current string object, delimited
by elements of a specified Unicode character array. The int parameter specifies the
maximum number of substrings to return.
31
Public Function StartsWith ( value As String ) As Boolean
Determines whether the beginning of this string instance matches the specified string.
32
Public Function ToCharArray As Char()
Returns a Unicode character array with all the characters in the current string object.
33
Public Function ToCharArray ( startIndex As Integer, length As Integer ) As Char()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 54/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Returns a Unicode character array with all the characters in the current string object,
starting from the specified index and up to the specified length.
34
Public Function ToLower As String
35
Public Function ToUpper As String
36
Public Function Trim As String
Removes all leading and trailing white-space characters from the current String object.
The above list of methods is not exhaustive, please visit MSDN library for the complete list of
methods and String class constructors.
Examples
The following example demonstrates some of the methods mentioned above −
Comparing Strings
Live Demo
Module strings
Sub Main()
Dim str1, str2 As String
str1 = "This is test"
str2 = "This is text"
When the above code is compiled and executed, it produces the following result −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 55/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Live Demo
Module strings
Sub Main()
Dim str1 As String
str1 = "This is test"
If (str1.Contains("test")) Then
Console.WriteLine("The sequence 'test' was found.")
End If
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Getting a Substring:
Live Demo
Module strings
Sub Main()
Dim str As String
str = "Last night I dreamt of San Pedro"
Console.WriteLine(str)
When the above code is compiled and executed, it produces the following result −
Joining Strings
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 56/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Live Demo
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()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
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)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 57/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 58/188
7/21/22, 1:32 PM VB.Net - Quick Guide
5 Hour Gets the hour component of the date represented by this instance.
6 Kind Gets a value that indicates whether the time represented by this
instance is based on local time, Coordinated Universal Time (UTC),
or neither.
8 Minute Gets the minute component of the date represented by this instance.
9 Month Gets the month component of the date represented by this instance.
10 Now Gets a DateTime object that is set to the current date and time on
this computer, expressed as the local time.
12 Ticks Gets the number of ticks that represent the date and time of this
instance.
15 UtcNow Gets a DateTime object that is set to the current date and time on
this computer, expressed as the Coordinated Universal Time (UTC).
16 Year Gets the year component of the date represented by this instance.
The following table lists some of the commonly used methods of the DateTime structure −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 59/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Public Function Add (value As TimeSpan) As DateTime
Returns a new DateTime that adds the value of the specified TimeSpan to the value of
this instance.
2
Public Function AddDays ( value As Double) As DateTime
Returns a new DateTime that adds the specified number of days to the value of this
instance.
3
Public Function AddHours (value As Double) As DateTime
Returns a new DateTime that adds the specified number of hours to the value of this
instance.
4
Public Function AddMinutes (value As Double) As DateTime
Returns a new DateTime that adds the specified number of minutes to the value of this
instance.
5
Public Function AddMonths (months As Integer) As DateTime
Returns a new DateTime that adds the specified number of months to the value of this
instance.
6
Public Function AddSeconds (value As Double) As DateTime
Returns a new DateTime that adds the specified number of seconds to the value of this
instance.
7
Public Function AddYears (value As Integer ) As DateTime
Returns a new DateTime that adds the specified number of years to the value of this
instance.
8
Public Shared Function Compare (t1 As DateTime,t2 As DateTime) As Integer
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 60/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Compares two instances of DateTime and returns an integer that indicates whether the
first instance is earlier than, the same as, or later than the second instance.
9
Public Function CompareTo (value As DateTime) As Integer
Compares the value of this instance to a specified DateTime value and returns an integer
that indicates whether this instance is earlier than, the same as, or later than the specified
DateTime value.
10
Public Function Equals (value As DateTime) As Boolean
Returns a value indicating whether the value of this instance is equal to the value of the
specified DateTime instance.
11
Public Shared Function Equals (t1 As DateTime, t2 As DateTime) As Boolean
Returns a value indicating whether two DateTime instances have the same date and time
value.
12
Public Overrides Function ToString As String
Converts the value of the current DateTime object to its equivalent string representation.
The above list of methods is not exhaustive, please visit Microsoft documentation for the
complete list of methods and properties of the DateTime structure.
By assigning the DateTime object a date and time value returned by a property or method.
Live Demo
Module Module1
Sub Main()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 61/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Console.WriteLine(date1)
Console.WriteLine(date2)
Console.WriteLine(date3)
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 −
Live Demo
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 62/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Current Date −
Live Demo
Module dateNtime
Sub Main()
Console.WriteLine("Current Date: ")
Dim dt As Date = Today
Console.WriteLine("Today is: {0}", dt)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
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.
Live Demo
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"))
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 63/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 64/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Format Description
General Date, or G Displays a date and/or time. For example, 1/12/2012 07:07:30 AM.
Long Date,Medium Date, Displays a date according to your current culture's long date format. For
or D example, Sunday, December 16, 2012.
Short Date, or d Displays a date using your current culture's short date format. For
example, 12/12/2012.
Long Time,Medium Time, Displays a time using your current culture's long time format; typically
orT includes hours, minutes, seconds. For example, 01:07:30 AM.
Short Time or t Displays a time using your current culture's short time format. For
example, 11:07 AM.
f Displays the long date and short time according to your current culture's
format. For example, Sunday, December 16, 2012 12:15 AM.
F Displays the long date and long time according to your current culture's
format. For example, Sunday, December 16, 2012 12:15:31 AM.
g Displays the short date and short time according to your current culture's
format. For example, 12/16/2012 12:15 AM.
M, m Displays the month and the day of a date. For example, December 16.
s Formats the date and time as a sortable index. For example, 2012-12-
16T12:07:31.
u Formats the date and time as a GMT sortable index. For example, 2012-
12-16 12:15:31Z.
U Formats the date and time with the long date and long time as GMT. For
example, Sunday, December 16, 2012 6:07:31 PM.
Y, y Formats the date as the year and month. For example, December, 2012.
For other formats like user-defined formats, please consult Microsoft Documentation .
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 65/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Date
Returns or sets a String value representing the current date according to your system.
2
Now
Returns a Date value containing the current date and time according to your system.
3
TimeOfDay
Returns or sets a Date value containing the current time of day according to your system.
4
Timer
Returns a Double value representing the number of seconds elapsed since midnight.
5
TimeString
Returns or sets a String value representing the current time of day according to your
system.
6
Today
The following table lists some of the commonly used methods of the DateAndTime class −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 66/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Public Shared Function DateAdd (Interval As DateInterval, Number As Double,
DateValue As DateTime) As DateTime
Returns a Date value containing a date and time value to which a specified time interval
has been added.
2
Public Shared Function DateAdd (Interval As String,Number As Double,DateValue
As Object ) As DateTime
Returns a Date value containing a date and time value to which a specified time interval
has been added.
3
Public Shared Function DateDiff (Interval As DateInterval, Date1 As DateTime,
Date2 As DateTime, DayOfWeek As FirstDayOfWeek, WeekOfYear As
FirstWeekOfYear ) As Long
Returns a Long value specifying the number of time intervals between two Date values.
4
Public Shared Function DatePart (Interval As DateInterval, DateValue As DateTime,
FirstDayOfWeekValue As FirstDayOfWeek, FirstWeekOfYearValue As
FirstWeekOfYear ) As Integer
Returns an Integer value containing the specified component of a given Date value.
5
Public Shared Function Day (DateValue As DateTime) As Integer
Returns an Integer value from 1 through 31 representing the day of the month.
6
Public Shared Function Hour (TimeValue As DateTime) As Integer
Returns an Integer value from 0 through 23 representing the hour of the day.
7
Public Shared Function Minute (TimeValue As DateTime) As Integer
Returns an Integer value from 0 through 59 representing the minute of the hour.
8
Public Shared Function Month (DateValue As DateTime) As Integer
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 67/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Returns an Integer value from 1 through 12 representing the month of the year.
9
Public Shared Function MonthName (Month As Integer, Abbreviate As Boolean) As
String
10
Public Shared Function Second (TimeValue As DateTime) As Integer
Returns an Integer value from 0 through 59 representing the second of the minute.
11
Public Overridable Function ToString As String
12
Public Shared Function Weekday (DateValue As DateTime, DayOfWeek As
FirstDayOfWeek) As Integer
Returns an Integer value containing a number representing the day of the week.
13
Public Shared Function WeekdayName (Weekday As Integer, Abbreviate As
Boolean, FirstDayOfWeekValue As FirstDayOfWeek) As String
14
Public Shared Function Year (DateValue As DateTime) As Integer
The above list is not exhaustive. For complete list of properties and methods of the DateAndTime
class, please consult Microsoft Documentation .
Live Demo
Module Module1
Sub Main()
Dim birthday As Date
Dim bday As Integer
Dim month As Integer
Dim monthname As String
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 68/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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
VB.Net - Arrays
An array stores a fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a collection of variables of
the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 69/188
7/21/22, 1:32 PM VB.Net - Quick Guide
You can also initialize the array elements while declaring the array. For example,
The elements in an array can be stored and accessed by using the index of the array. The following
program demonstrates this −
Live Demo
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Element(0) = 100
Element(1) = 101
Element(2) = 102
Element(3) = 103
Element(4) = 104
Element(5) = 105
Element(6) = 106
Element(7) = 107
Element(8) = 108
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 70/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Element(9) = 109
Element(10) = 110
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the
program. You can declare a dynamic array using the ReDim statement.
Where,
The Preserve keyword helps to preserve the data in an existing array, when you resize it.
Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 71/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
0 85
1 75
2 90
3 80
4 76
5 92
6 99
7 79
8 75
9 0
10 0
Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called rectangular arrays.
Live Demo
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
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 72/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8
Jagged Array
A Jagged array is an array of arrays. The following code shows declaring a jagged array named
scores of Integers −
Live Demo
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
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 73/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 74/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
IsFixedSize
2
IsReadOnly
3
Length
Gets a 32-bit integer that represents the total number of elements in all the dimensions
of the Array.
4
LongLength
Gets a 64-bit integer that represents the total number of elements in all the dimensions
of the Array.
5
Rank
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 75/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Public Shared Sub Clear (array As Array, index As Integer, length As Integer)
Sets a range of elements in the Array to zero, to false, or to null, depending on the
element type.
2
Public Shared Sub Copy (sourceArray As Array, destinationArray As Array, length
As Integer)
Copies a range of elements from an Array starting at the first element and pastes them
into another Array starting at the first element. The length is specified as a 32-bit integer.
3
Public Sub CopyTo (array As Array, index As Integer)
Copies all the elements of the current one-dimensional Array to the specified one-
dimensional Array starting at the specified destination Array index. The index is specified
as a 32-bit integer.
4
Public Function GetLength (dimension As Integer) As Integer
Gets a 32-bit integer that represents the number of elements in the specified dimension
of the Array.
5
Public Function GetLongLength (dimension As Integer) As Long
Gets a 64-bit integer that represents the number of elements in the specified dimension
of the Array.
6
Public Function GetLowerBound (dimension As Integer) As Integer
7
Public Function GetType As Type
8
Public Function GetUpperBound (dimension As Integer) As Integer
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 76/188
7/21/22, 1:32 PM VB.Net - Quick Guide
9
Public Function GetValue (index As Integer) As Object
Gets the value at the specified position in the one-dimensional Array. The index is
specified as a 32-bit integer.
10
Public Shared Function IndexOf (array As Array,value As Object) As Integer
Searches for the specified object and returns the index of the first occurrence within the
entire one-dimensional Array.
11
Public Shared Sub Reverse (array As Array)
12
Public Sub SetValue (value As Object, index As Integer)
Sets a value to the element at the specified position in the one-dimensional Array. The
index is specified as a 32-bit integer.
13
Public Shared Sub Sort (array As Array)
14
Public Overridable Function ToString As String
Returns a string that represents the current object (Inherited from Object).
For complete list of Array class properties and methods, please consult Microsoft documentation.
Example
The following program demonstrates use of some of the methods of the Array class:
Live Demo
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: ")
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 77/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72
VB.Net - Collections
Collection classes are specialized classes for data storage and retrieval. These classes provide
support for stacks, queues, lists, and hash tables. Most collection classes implement the same
interfaces.
Collection classes serve various purposes, such as allocating memory dynamically to elements and
accessing a list of items on the basis of an index, etc. These classes create collections of objects of
the Object class, which is the base class for all data types in VB.Net.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 78/188
7/21/22, 1:32 PM VB.Net - Quick Guide
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 79/188
7/21/22, 1:32 PM VB.Net - Quick Guide
A hash table is used when you need to access elements by using key, and
you can identify a useful key value. Each item in the hash table has a
key/value pair. The key is used to access the items in the collection.
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.
It is used when you need a first-in, first-out access of items. When you add an
item in the list, it is called enqueue, and when you remove an item, it is called
deque.
BitArray It represents an array of the binary representation using the values 1 and 0.
It is used when you need to store the bits but do not know the number of bits
in advance. You can access items from the BitArray collection by using an
integer index, which starts from zero.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 80/188
7/21/22, 1:32 PM VB.Net - Quick Guide
VB.Net - Functions
A procedure is a group of statements that together perform a task when called. After the procedure
is executed, the control returns to the statement calling the procedure. VB.Net has two types of
procedures −
Functions
Sub procedures or Subs
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 −
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.
Else
result = num2
End If
FindMax = result
End Function
Live Demo
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 82/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Recursive Function
A function can call itself. This is known as recursion. Following is an example that calculates
factorial for a given number using a recursive function −
Live Demo
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
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.
Live Demo
Module myparamfunc
Function AddElements(ParamArray arr As Integer()) As Integer
Dim sum As Integer = 0
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 83/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Dim i As Integer = 0
When the above code is compiled and executed, it produces the following result −
Live Demo
Module arrayParameter
Function getAverage(ByVal arr As Integer(), ByVal size As Integer) As Double
'local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0
For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Return avg
End Function
Sub Main()
' an int array with 5 elements '
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
'pass pointer to the array as an argument
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 84/188
7/21/22, 1:32 PM VB.Net - Quick Guide
avg = getAverage(balance, 5)
' output the returned value '
Console.WriteLine("Average value is: {0} ", avg)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Where,
Modifiers − specify the access level of the procedure; possible values are - Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing,
and shadowing.
Example
The following example demonstrates a Sub procedure CalculatePay that takes two parameters
hours and wages and displays the total pay of an employee −
Live Demo
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 85/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Module mysub
Sub CalculatePay(ByRef hours As Double, ByRef wage As Decimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePay Sub Procedure
CalculatePay(25, 10)
CalculatePay(40, 20)
CalculatePay(30, 27.5)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
In VB.Net, you declare the reference parameters using the ByVal keyword. The following example
demonstrates the concept −
Live Demo
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 86/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
It shows that there is no change in the values though they had been changed inside the function.
In VB.Net, you declare the reference parameters using the ByRef keyword. The following example
demonstrates this −
Live Demo
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As Integer)
Dim temp As Integer
temp = x ' save the value of x
x = y ' put y into x
y = temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 87/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
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 −
Where,
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 88/188
7/21/22, 1:32 PM VB.Net - Quick Guide
accessmodifier defines the access levels of the class, it has values as - Public, Protected,
Friend, Protected Friend and Private. Optional.
Shadows indicate that the variable re-declares and hides an identically named element, or set
of overloaded elements, in a base class. Optional.
MustInherit specifies that the class can be used only as a base class and that you cannot
create an object directly from it, i.e., an abstract class. Optional.
NotInheritable specifies that the class cannot be used as a base class.
The following example demonstrates a Box class, with three data members, length, breadth and
height −
Live Demo
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 89/188
7/21/22, 1:32 PM VB.Net - Quick Guide
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Member variables are attributes of an object (from design perspective) and they are kept private to
implement encapsulation. These variables can only be accessed using the public member functions.
Let us put above concepts to set and get the value of different class members in a class −
Live Demo
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public Sub setLength(ByVal len As Double)
length = len
End Sub
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Live Demo
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 91/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Class Line
Private length As Double ' Length of a line
Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub
When the above code is compiled and executed, it produces the following result −
A default constructor does not have any parameter, but if you need, a constructor can have
parameters. Such constructors are called parameterized constructors. This technique helps you
to assign initial value to an object at the time of its creation as shown in the following example −
Live Demo
Class Line
Private length As Double ' Length of a line
Public Sub New(ByVal len As Double) 'parameterised constructor
Console.WriteLine("Object is being created, length = {0}", len)
length = len
End Sub
Public Sub setLength(ByVal len As Double)
length = len
End Sub
When the above code is compiled and executed, it produces the following result −
A destructor is a special member Sub of a class that is executed whenever an object of its class
goes out of scope.
A destructor has the name Finalize and it can neither return a value nor can it take any
parameters. Destructor can be very useful for releasing resources before coming out of the program
like closing files, releasing memories, etc.
Live Demo
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 93/188
7/21/22, 1:32 PM VB.Net - Quick Guide
End Sub
When the above code is compiled and executed, it produces the following result −
The keyword Shared implies that only one instance of the member exists for a class. Shared
variables are used for defining constants because their values can be retrieved by invoking the class
without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You can also
initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared
variables. The Shared functions exist even before the object is created.
Live Demo
Class StaticVar
Public Shared num As Integer
Public Sub count()
num = num + 1
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 94/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 −
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 95/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Live Demo
' Base class
Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As Integer)
height = h
End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New Rectangle()
rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Total area: 35
Live Demo
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 96/188
7/21/22, 1:32 PM VB.Net - Quick Guide
'Derived class
Class Tabletop : Inherits Rectangle
Private cost As Double
Public Sub New(ByVal l As Double, ByVal w As Double)
MyBase.New(l, w)
End Sub
Public Function GetCost() As Double
Dim cost As Double
cost = GetArea() * 70
Return cost
End Function
Public Overrides Sub Display()
MyBase.Display()
Console.WriteLine("Cost: {0}", GetCost())
End Sub
'end class Tabletop
End Class
Class RectangleTester
Shared Sub Main()
Dim t As Tabletop = New Tabletop(4.5, 7.5)
t.Display()
Console.ReadKey()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 97/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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
Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords - Try, Catch, Finally and Throw.
Try − A Try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more Catch blocks.
Catch − A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The Catch keyword indicates the catching of an
exception.
Finally − The Finally block is used to execute a given set of statements, whether an exception
is thrown or not thrown. For example, if you open a file, it must be closed whether an exception
is raised or not.
Throw − A program throws an exception when a problem shows up. This is done using a
Throw keyword.
Syntax
Assuming a block will raise an exception, a method catches an exception using a combination of the
Try and Catch keywords. A Try/Catch block is placed around the code that might generate an
exception. Code within a Try/Catch block is referred to as protected code, and the syntax for using
Try/Catch looks like the following −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 98/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
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.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 99/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 −
Live Demo
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
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 100/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
Live Demo
Module exceptionProg
Public Class TempIsZeroException : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Temperature
Dim temperature As Integer = 0
Sub showTemp()
If (temperature = 0) Then
Throw (New TempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
End If
End Sub
End Class
Sub Main()
Dim temp As Temperature = New Temperature()
Try
temp.showTemp()
Catch e As TempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 101/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 ]
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 −
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).
The System.IO namespace has various classes that are used for performing various operations with
files, like creating and deleting files, reading from or writing to a file, closing a file, etc.
The following table shows some commonly used non-abstract classes in the System.IO namespace
−
You need to create a FileStream object to create a new file or open an existing file. The syntax for
creating a FileStream object is as follows −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 103/188
7/21/22, 1:32 PM VB.Net - Quick Guide
For example, for creating a FileStream object F for reading a file named sample.txt −
Parameter Description
FileMode
The FileMode enumerator defines various methods for opening files. The
members of the FileMode enumerator are −
Append − It opens an existing file and puts cursor at the end of file, or
creates the file, if the file does not exist.
Truncate − It opens an existing file and truncates its size to zero bytes.
FileAccess
FileAccess enumerators have members: Read, ReadWrite and Write.
FileShare
FileShare enumerators have the following members −
Example
The following program demonstrates use of the FileStream class −
Live Demo
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 104/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Imports System.IO
Module fileProg
Sub Main()
Dim f1 As FileStream = New FileStream("sample.txt", _ FileMode.OpenOrCreate, Fi
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
We will discuss these classes and the operations they perform in the following sections. Please click
the links provided to get to the individual sections −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 105/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Reading from and Writing into Text files
It involves reading from and writing into text files. The StreamReader and StreamWriter
classes help to accomplish it.
2
Reading from and Writing into Binary files
It involves reading from and writing into binary files. The BinaryReader and
BinaryWriter classes help to accomplish this.
3
Manipulating the Windows file system
It gives a VB.Net programmer the ability to browse and locate Windows files and
directories.
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.
Where
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 106/188
7/21/22, 1:32 PM VB.Net - Quick Guide
For example,
Form1.Caption = "Hello"
You can set any of the form properties using Properties Window. Most of the properties can be set
or read during application execution. You can refer to Microsoft documentation for a complete list of
properties associated with different controls and restrictions applied to them.
Control Methods
A method is a procedure created as a member of a class and they cause an object to do something.
Methods are used to access or manipulate the characteristics of an object or a variable. There are
mainly two categories of methods you will use in your classes −
If you are using a control such as one of those provided by the Toolbox, you can call any of its
public methods. The requirements of such a method depend on the class being used.
If none of the existing methods can perform your desired task, you can add a method to a
class.
For example, the MessageBox control has a method named Show, which is called in the code
snippet below −
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
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 107/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 −
Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event. Similar
way, you can check stub code for click, double click. If you want to initialize some variables like
properties, etc., then you will keep such code inside Form1_Load() subroutine. Here, important point
to note is the name of the event handler, which is by default Form1_Load, but you can change this
name based on your naming convention you use in your application programming.
Basic Controls
VB.Net provides a huge variety of controls that help you to create rich user interface. Functionalities
of all these controls are defined in the respective control classes. The control classes are defined in
the System.Windows.Forms namespace.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 108/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Forms
The container for all the controls that make up the user interface.
2
TextBox
3
Label
4
Button
5
ListBox
6
ComboBox
7
RadioButton
It enables the user to select a single option from a group of choices when paired with
other RadioButton controls.
8
CheckBox
9
PictureBox
10
ProgressBar
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 109/188
7/21/22, 1:32 PM VB.Net - Quick Guide
11
ScrollBar
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
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.
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 110/188
7/21/22, 1:32 PM VB.Net - Quick Guide
All these above-mentioned classes have corresponding controls that could be added from the
Toolbox during design time. You can include relevant functionality of these classes to your
application, either by instantiating the class programmatically or by using relevant controls.
When you double click any of the dialog controls in the toolbox or drag the control onto the form, it
appears in the Component tray at the bottom of the Windows Forms Designer, they do not directly
show up on the form.
The following table lists the commonly used dialog box controls. Click the following links to check
their detail −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 111/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
ColorDialog
It represents a common dialog box that displays available colors along with controls that
enable the user to define custom colors.
2
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.
3
OpenFileDialog
It prompts the user to open a file and allows the user to select a file to open.
4
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.
5
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 112/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Traditionally, the Menu, MainMenu, ContextMenu, and MenuItem classes were used for adding
menus, sub-menus and context menus in a Windows application.
Let us create a typical windows main menu bar and sub menus using the old version controls first
since these controls are still much used in old applications.
Following is an example, which shows how we create a menu bar with menu items: File, Edit, View
and Project. The File menu has the sub menus New, Open and Save.
Let's double click on the Form and put the following code in the opened window.
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 −
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 114/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
MenuStrip
2
ToolStripMenuItem
3
ContextMenuStrip
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 115/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Clear
2
ContainsData
Indicates whether there is data on the Clipboard that is in the specified format or can be
converted to that format.
3
ContainsImage
Indicates whether there is data on the Clipboard that is in the Bitmap format or can be
converted to that format.
4
ContainsText
Indicates whether there is data on the Clipboard in the Text or UnicodeText format,
depending on the operating system.
5
GetData
6
GetDataObject
7
GetImage
8
GetText
Retrieves text data from the Clipboard in the Text or UnicodeText format, depending on
the operating system.
9
GetText(TextDataFormat)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 116/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 117/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 −
When you anchor a control to a form, the control maintains its distance from the edges of the form
and its anchored position, when the form is resized.
You can set the Anchor property values of a control from the Properties window −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 118/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 119/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Docking of a control means docking it to one of the edges of its container. In docking, the control
fills certain area of the container completely.
The Dock property of the Control class does this. The Dock property gets or sets which control
borders are docked to its parent control and determines how a control is resized with its parent.
You can set the Dock property values of a control from the Properties window −
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 120/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 121/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Change the text properties of the buttons to OK and Cancel, respectively. Change the text
properties of the label to 'Enter your name:'.
Set the FormBorderStyle property of Form2 to FixedDialog, for giving it a dialog box border.
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 122/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 123/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
Mouse events
Keyboard events
MouseMove − it occurs when the mouse pointer moves over the control
MouseUp − it occurs when the mouse pointer is over the control and the mouse button is
released
MouseWheel − it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of type MouseEventArgs. The
MouseEventArgs object is used for handling mouse events. It has the following properties −
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 124/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −
Try to enter text in the text boxes and check the mouse events −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 126/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 −
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.
Add the following codes for handling the KeyUP events of the text box txtID.
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 128/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 −
Character escapes
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 129/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Character classes
Anchors
Grouping constructs
Quantifiers
Backreference constructs
Alternation constructs
Substitutions
Miscellaneous constructs
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 130/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Public Function IsMatch (input As String) As Boolean
Indicates whether the regular expression specified in the Regex constructor finds a
match in a specified input string.
2
Public Function IsMatch (input As String, startat As Integer ) As Boolean
Indicates whether the regular expression specified in the Regex constructor finds a
match in the specified input string, beginning at the specified starting position in the
string.
3
Public Shared Function IsMatch (input As String, pattern As String ) As Boolean
Indicates whether the specified regular expression finds a match in the specified input
string.
4
Public Function Matches (input As String) As MatchCollection
Searches the specified input string for all occurrences of a regular expression.
5
Public Function Replace (input As String, replacement As String) As String
In a specified input string, replaces all strings that match a regular expression pattern
with a specified replacement string.
6
Public Function Split (input As String) As String()
Splits an input string into an array of substrings at the positions defined by a regular
expression pattern specified in the Regex constructor.
For the complete list of methods and properties, please consult Microsoft documentation.
Example 1
The following example matches words that start with 'S' −
Live Demo
Imports System.Text.RegularExpressions
Module regexProg
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 131/188
7/21/22, 1:32 PM VB.Net - Quick Guide
For Each m In mc
Console.WriteLine(m)
Next m
End Sub
Sub Main()
Dim str As String = "A Thousand Splendid Suns"
Console.WriteLine("Matching words that start with 'S': ")
showMatch(str, "\bS\S*")
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Example 2
The following example matches words that start with 'm' and ends with 'e' −
Live Demo
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()
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 132/188
7/21/22, 1:32 PM VB.Net - Quick Guide
When the above code is compiled and executed, it produces the following result −
Example 3
This example replaces extra white space −
Live Demo
Imports System.Text.RegularExpressions
Module regexProg
Sub Main()
Dim input As String = "Hello World "
Dim pattern As String = "\\s+"
Dim replacement As String = " "
Dim rgx As Regex = New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement)
When the above code is compiled and executed, it produces the following result −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 133/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Microsoft ActiveX Data Objects.Net (ADO.Net) is a model, a part of the .Net framework that is used
by the .Net applications for retrieving, accessing and updating data.
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.
Datasets store data in a disconnected cache and the application retrieves data from it.
Data readers provide data to the application in a read-only and forward-only mode.
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 134/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Connection
2
Command
3
DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-only
mode.
4
DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a
database through a data adapter. It retrieves data from a database into a dataset and
updates the database. When changes are made to the dataset, the changes in the
database are actually done by the data adapter.
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.
The EntityClient provider - enables accessing data through Entity Data Model (EDM)
applications.
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
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 135/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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 DataSet class is present in the System.Data namespace. The following table describes all the
components of DataSet −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 136/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
DataTableCollection
2
DataRelationCollection
3
ExtendedProperties
It contains additional information, like the SQL statement for retrieving data, time of
retrieval, etc.
4
DataTable
5
DataRelation
6
DataRowCollection
7
DataView
8
PrimaryKey
9
DataRow
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 137/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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
11
DataColumn
Connecting to a Database
The .Net Framework provides two types of Connection classes −
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 138/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Select a server name and the database name in the Add Connection dialog box.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 139/188
7/21/22, 1:32 PM VB.Net - Quick Guide
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 140/188
7/21/22, 1:32 PM VB.Net - Quick Guide
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 141/188
7/21/22, 1:32 PM VB.Net - Quick Guide
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 142/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Choose the database object, Customers table in our example, and click the Finish button.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 143/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Select the Preview Data link to see the data in the Results grid −
When the application is run using Start button available at the Microsoft Visual Studio tool bar, it will
show the following window −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 144/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 146/188
7/21/22, 1:32 PM VB.Net - Quick Guide
We have discussed that the DataSet components like DataTable, DataColumn and DataRow allow
us to create tables, columns and rows, respectively.
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.
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 148/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Clicking the Fill button displays the table on the data grid view control −
To avail this interoperability in your application, you need to import the namespace
Microsoft.Office.Interop.Excel in your Windows Form Application.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 149/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Finally, select OK, Microsoft Visual Studio creates your project and displays following Form1.
On the COM tab, locate Microsoft Excel Object Library and then click Select.
Click OK.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 150/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Double click the code window and populate the Click event of Button1, as shown below.
students(4 1) = "Ayman"
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 151/188
7/21/22, 1:32 PM VB.Net - Quick Guide
students(4, 1) = Ayman
' Fill A2:B6 with an array of values (First and Last Names).
shXL.Range("A2", "B6").Value = students
' Fill C2:C6 with a relative formula (=A2 & " " & B2).
raXL = shXL.Range("C2", "C6")
raXL.Formula = "=A2 & "" "" & B2"
' Make sure Excel is visible and give the user control
' of Excel's lifetime.
appXL.Visible = True
appXL.UserControl = True
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 152/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Clicking on the Button would display the following excel sheet. You will be asked to save the
workbook.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 153/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Attachment
2
AttachmentCollection
3
MailAddress
4
MailAddressCollection
5
MailMessage
Represents an e-mail message that can be sent using the SmtpClient class.
6
SmtpClient
Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).
7
SmtpException
Represents the exception that is thrown when the SmtpClient is not able to complete a
Send or SendAsync operation.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 154/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
ClientCertificates
Specifies which certificates should be used to establish the Secure Sockets Layer (SSL)
connection.
2
Credentials
3
EnableSsl
Specifies whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the
connection.
4
Host
Gets or sets the name or IP address of the host used for SMTP transactions.
5
Port
6
Timeout
Gets or sets a value that specifies the amount of time after which a synchronous Send
call times out.
7
UseDefaultCredentials
Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with
requests.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 155/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
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.
2
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.
3
OnSendCompleted
4
Send(MailMessage)
5
Send(String, String, String, String)
Sends the specified e-mail message to an SMTP server for delivery. The message
sender, recipients, subject, and message body are specified using String objects.
6
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.
7
SendAsync(String, String, String, String, Object)
Sends an e-mail message to an SMTP server for delivery. The message sender,
recipients, subject, and message body are specified using String objects. 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.
8
SendAsyncCancel
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 156/188
7/21/22, 1:32 PM VB.Net - Quick Guide
9
SendMailAsync(MailMessage)
10
SendMailAsync(String, String, String, String)
11
ToString
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.To properties, respectively.
You should also specify the message content using the MailMessage.Body property.
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.
Change the text property of the button control to 'Send'
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 157/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 158/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 159/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
XmlAttribute
Represents an attribute. Valid and default values for the attribute are defined in a
document type definition (DTD) or schema.
2
XmlCDataSection
3
XmlCharacterData
4
XmlComment
5
XmlConvert
Encodes and decodes XML names and provides methods for converting between
common language runtime types and XML Schema definition language (XSD) types.
When converting data types, the values returned are locale independent.
6
XmlDeclaration
7
XmlDictionary
8
XmlDictionaryReader
An abstract class that the Windows Communication Foundation (WCF) derives from
XmlReader to do serialization and deserialization.
9
XmlDictionaryWriter
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 160/188
7/21/22, 1:32 PM VB.Net - Quick Guide
10
XmlDocument
11
XmlDocumentFragment
12
XmlDocumentType
13
XmlElement
Represents an element.
14
XmlEntity
15
XmlEntityReference
16
XmlException
17
XmlImplementation
18
XmlLinkedNode
19
XmlNode
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 161/188
7/21/22, 1:32 PM VB.Net - Quick Guide
20
XmlNodeList
21
XmlNodeReader
Represents a reader that provides fast, non-cached forward only access to XML data in
an XmlNode.
22
XmlNotation
23
XmlParserContext
Provides all the context information required by the XmlReader to parse an XML
fragment.
24
XmlProcessingInstruction
25
XmlQualifiedName
26
XmlReader
Represents a reader that provides fast, noncached, forward-only access to XML data.
27
XmlReaderSettings
Specifies a set of features to support on the XmlReader object created by the Create
method.
28
XmlResolver
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 162/188
7/21/22, 1:32 PM VB.Net - Quick Guide
29
XmlSecureResolver
30
XmlSignificantWhitespace
Represents white space between markup in a mixed content node or white space within
an xml:space= 'preserve' scope. This is also referred to as significant white space.
31
XmlText
32
XmlTextReader
Represents a reader that provides fast, non-cached, forward-only access to XML data.
33
XmlTextWriter
34
XmlUrlResolver
35
XmlWhitespace
36
XmlWriter
37
XmlWriterSettings
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 163/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
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 −
The XmlReader class is used to read XML data in a fast, forward-only and non-cached manner. It
reads an XML document or a stream.
Example 1
This example demonstrates reading XML data from the file movies.xml.
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
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 165/188
7/21/22, 1:32 PM VB.Net - Quick Guide
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 166/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xws As XmlWriterSettings = New XmlWriterSettings()
xws.Indent = True
xws.NewLineOnAttributes = True
Dim xw As XmlWriter = XmlWriter.Create("authors.xml", xws)
xw.WriteStartDocument()
xw.WriteStartElement("Authors")
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "1")
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 167/188
7/21/22, 1:32 PM VB.Net - Quick Guide
xw.WriteElementString("fname", "Zara")
xw.WriteElementString("lname", "Ali")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "2")
xw.WriteElementString("fname", "Priya")
xw.WriteElementString("lname", "Sharma")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "3")
xw.WriteElementString("fname", "Anshuman")
xw.WriteElementString("lname", "Mohan")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "4")
xw.WriteElementString("fname", "Bibhuti")
xw.WriteElementString("lname", "Banerjee")
xw.WriteEndElement()
xw.WriteStartElement("author")
xw.WriteAttributeString("code", "5")
xw.WriteElementString("fname", "Riyan")
xw.WriteElementString("lname", "Sengupta")
xw.WriteEndElement()
xw.WriteEndElement()
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 168/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Following are some of the commonly used methods of the XmlDocument class −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 169/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
AppendChild
Adds the specified node to the end of the list of child nodes, of this node.
2
CreateAttribute(String)
3
CreateComment
4
CreateDefaultAttribute
Creates a default attribute with the specified prefix, local name and namespace URI.
5
CreateElement(String)
6
CreateNode(String, String, String)
Creates an XmlNode with the specified node type, Name, and NamespaceURI.
7
CreateNode(XmlNodeType, String, String)
8
CreateNode(XmlNodeType, String, String, String)
9
CreateProcessingInstruction
10
CreateSignificantWhitespace
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 170/188
7/21/22, 1:32 PM VB.Net - Quick Guide
11
CreateTextNode
12
CreateWhitespace
13
CreateXmlDeclaration
14
GetElementById
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)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 171/188
7/21/22, 1:32 PM VB.Net - Quick Guide
20 Load(String)
21
Load(TextReader)
22
Load(XmlReader)
23
LoadXml
24
PrependChild
Adds the specified node to the beginning of the list of child nodes for this node.
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
28
ReplaceChild
29
Save(Stream)
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 172/188
7/21/22, 1:32 PM VB.Net - Quick Guide
30 Save(String)
31
Save(TextWriter)
32
Save(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.
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
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
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 174/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Server-side scripting − these are programs executed on a web server, written using server-
side scripting languages like ASP (Active Server Pages) or JSP (Java Server Pages).
Client-side scripting − these are programs executed on the browser, written using scripting
languages like JavaScript, VBScript, etc.
ASP.Net is the .Net version of ASP, introduced by Microsoft, for creating dynamic web pages by
using server-side scripts. ASP.Net applications are compiled codes written using the extensible and
reusable components or objects present in .Net framework. These codes can use the entire
hierarchy of classes in .Net framework.
The ASP.Net application codes could be written in either of the following languages −
Jscript
J#
In this chapter, we will give a very brief introduction to writing ASP.Net applications using VB.Net.
For detailed discussion, please consult the ASP.Net Tutorial.
The following table lists the ASP.Net built-in objects with a brief description −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 175/188
7/21/22, 1:32 PM VB.Net - Quick Guide
1
Application
Describes the methods, properties, and collections of the object that stores information
related to the entire Web application, including variables and objects that exist for the
lifetime of the application.
You use this object to store and retrieve information to be shared among all users of an
application. For example, you can use an Application object to create an e-commerce
page.
2
Request
Describes the methods, properties, and collections of the object that stores information
related to the HTTP request. This includes forms, cookies, server variables, and
certificate data.
You use this object to access the information sent in a request from a browser to the
server. For example, you can use a Request object to access information entered by a
user in an HTML form.
3
Response
Describes the methods, properties, and collections of the object that stores information
related to the server's response. This includes displaying content, manipulating headers,
setting locales, and redirecting requests.
You use this object to send information to the browser. For example, you use a
Response object to send output from your scripts to a browser.
4
Server
Describes the methods and properties of the object that provides methods for various
server tasks. With these methods you can execute code, get error conditions, encode
text strings, create objects for use by the Web page, and map physical paths.
You use this object to access various utility functions on the server. For example, you
may use the Server object to set a time out for a script.
5
Session
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 176/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Describes the methods, properties, and collections of the object that stores information
related to the user's session, including variables and objects that exist for the lifetime of
the session.
You use this object to store and retrieve information about particular user sessions. For
example, you can use Session object to keep information about the user and his
preference and keep track of pending operations.
Web Forms − this enables you to create the user interface and the application logic that would
be applied to various components of the user interface.
WCF Services − this enables you to remote access some server-side functionalities.
For this chapter, you need to use Visual Studio Web Developer, which is free. The IDE is almost
same as you have already used for creating the Windows Applications.
Web Forms
Web forms consists of −
User interface
Application logic
User interface consists of static HTML or XML elements and ASP.Net server controls. When you
create a web application, HTML or XML elements and server controls are stored in a file with .aspx
extension. This file is also called the page file.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 177/188
7/21/22, 1:32 PM VB.Net - Quick Guide
The application logic consists of code applied to the user interface elements in the page. You write
this code in any of .Net language like, VB.Net, or C#. The following figure shows a Web Form in
Design view −
Example
Let us create a new web site with a web form, which will show the current date and time, when a
user clicks a button. Take the following steps −
Select File → New → Web Site. The New Web Site Dialog Box appears.
Select the ASP.Net Empty Web Site templates. Type a name for the web site and select a
location for saving the files.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 178/188
7/21/22, 1:32 PM VB.Net - Quick Guide
You need to add a Default page to the site. Right click the web site name in the Solution
Explorer and select Add New Item option from the context menu. The Add New Item dialog box
is displayed −
Select Web Form option and provide a name for the default page. We have kept it as
Default.aspx. Click the Add button.
Set the title for the Default web page by adding a value to the <Title> tag of the page, in the
Source view −
To add controls on the web page, go to the design view. Add three labels, a text box and a
button on the form.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 179/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Double-click the button and add the following code to the Click event of the button −
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 −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 180/188
7/21/22, 1:32 PM VB.Net - Quick Guide
Web Services
A web service is a web application, which is basically a class consisting of methods that could be
used by other applications. It also follows a code-behind architecture like the ASP.Net web pages,
although it does not have an user interface.
The previous versions of .Net Framework used this concept of ASP.Net Web Service, which had
.asmx file extension. However, from .Net Framework 4.0 onwards, the Windows Communication
Foundation (WCF) technology has evolved as the new successor of Web Services, .Net Remoting
and some other related technologies. It has rather clubbed all these technologies together. In the
next section, we will provide a brief introduction to Windows Communication Foundation(WCF).
If you are using previous versions of .Net Framework, you can still create traditional web services.
Please consult ASP.Net - Web Services tutorial for detailed description.
Like Web services, WCF services also enable communication between applications. However,
unlike web services, the communication here is not limited to HTTP only. WCF can be configured to
be used over HTTP, TCP, IPC, and Message Queues. Another strong point in favour of WCF is, it
provides support for duplex communication, whereas with web services we could achieve simplex
communication only.
From beginners' point of view, writing a WCF service is not altogether so different from writing a
Web Service. To keep the things simple, we will see how to −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 181/188
7/21/22, 1:32 PM VB.Net - Quick Guide
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.
Select WCF Service template from list of templates −
Provide a name and location for the WCF Service and click OK.
A new WCF Service is created.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 182/188
7/21/22, 1:32 PM VB.Net - Quick Guide
A service contract defines the operation that a service performs. In the WCF Service application,
you will find two files automatically created in the App_Code folder in the Solution Explorer
IService.vb − this will have the service contract; in simpler words, it will have the interface for
the service, with the definitions of methods the service will provide, which you will implement in
your service.
Replace the code of the IService.vb file with the given code −
<OperationContract()>
Function GetName(ByVal symbol As String) As String
End Interface
' NOTE: You can use the "Rename" command on the context menu to change the class name
Public Class Service
Implements IService
Public Sub New()
End Sub
Dim stocks As String(,) =
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 183/188
7/21/22, 1:32 PM VB.Net - Quick Guide
{
{"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
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 184/188
7/21/22, 1:32 PM VB.Net - Quick Guide
To run the WCF Service, so created, select the Debug → Start Debugging option from the menu bar.
The output would be −
For testing the service operations, double click the name of the operation from the tree on the left
pane. A new tab will appear on the right pane.
Enter the value of parameters in the Request area of the right pane and click the 'Invoke' button.
The following diagram displays the result of testing the GetPrice operation −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 185/188
7/21/22, 1:32 PM VB.Net - Quick Guide
The following diagram displays the result of testing the GetName operation −
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.
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 186/188
7/21/22, 1:32 PM VB.Net - Quick Guide
We need to add a service reference to the WCF service we just created. Right click the website
in the Solution Explorer and select Add Service Reference option. This opens the Add Service
Reference Dialog box.
Enter the URL(location) of the Service in the Address text box and click the Go button. It
creates a service reference with the default name ServiceReference1. Click the OK button.
Creates the Address and Binding for the service in the web.config file.
Creates a proxy class to access the service.
Double click the Get Price button in the form, to enter the following code snippet on its Click
event −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 187/188
7/21/22, 1:32 PM VB.Net - Quick Guide
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, the following page opens in the browser −
Enter a symbol and click the Get Price button to get the hard-coded price −
https://www.tutorialspoint.com/vb.net/vb.net_quick_guide.htm 188/188