Você está na página 1de 293

VB.

NET
VB.NET Tutorial and source code
Visual Basic .NET is the most productive tool for rapidly creating a wide range of Windows,
Web, Mobile, and ffice applications built on the .NET !ramewor". The Visual Basic language
is designed to be human readable and accessible to everyone from novice programmers to
advanced system architects. #ll of this is built on top of the .NET !ramewor", which guarantees
that programs written in Visual Basic run with unsurpassed scalability and reliability. $rograms
written in Visual Basic will interoperate seamlessly with programs written in any other .NET
languages such as Visual %&, Visual '&, or Visual %((.
) hope this site will help you to ac*uire the s"ills and "nowledge necessary to develop Windows
applications in VB.NET in a simplified manner rather than in a comple+ way.
The Microsoft .Net !ramewor" is a platform that provides tools and technologies you need to
build Networ"ed #pplications as well as ,istributed Web -ervices and Web #pplications. The
.Net !ramewor" provides the necessary compile time and run.time foundation to build and run
any language that conforms to the %ommon /anguage -pecification 0%/-1.The main two
components of .Net !ramewor" are %ommon /anguage 2untime 0%/21 and .Net !ramewor"
%lass /ibrary 0!%/1.
The %ommon /anguage 2untime 0%/21 is the runtime environment of the .Net !ramewor" , that
e+ecutes and manages all running code li"e a Virtual Machine. The .Net !ramewor" %lass
/ibrary 0!%/1 is a huge collection of language.independent and type.safe reusable classes.
The .Net !ramewor" %lass /ibraries 0!%/1 are arranged into a logical grouping according to
their functionality and usability is called Namespaces. )n the following sections describes how to
.Net !ramewor" manages the code in compile time and run time.
Microsoft .Net /anguages -ource %ode are compiled into Microsoft )ntermediate /anguage
0M-)/1 . M-)/ we can call it as )ntermediate /anguage 0)/1 or %ommon )ntermediate /anguage
0%)/1. Microsoft )ntermediate /anguage 0M-)/1 is a %$3 independent set of instructions that
can be converted to the native code. Metadata also created in the course of compile time with
Microsoft )ntermediate /anguage 0M-)/1 and stored it with the compiled code . Metadata is
completely self.describing . Metadata is stored in a file called Manifest, and it contains
information about the members, types, references and all the other data that the %ommon
/anguage 2untime 0%/21 needs for e+ecution .
The %ommon /anguage 2untime 0%/21 uses metadata to locate and load classes, generate
native code, provide security, and e+ecute Managed %ode. Both Microsoft )ntermediate
/anguage 0M-)/1 and Metadata assembled together is "nown as $ortable E+ecutable 0$E1 file.
$ortable E+ecutable 0$E1 is supposed to be portable across all 45.bit operating systems by
Microsoft .Net !ramewor".
,uring the runtime the %ommon /anguage 2untime 0%/216s 'ust )n Time 0')T1 compiler
converts the Microsoft )ntermediate /anguage 0M-)/1 code into native code to the perating
-ystem. The native code is perating -ystem independent and this code is "nown as Managed
%ode , that is, the language6s functionality is managed by the .NET !ramewor" . The %ommon
/anguage 2untime 0%/21 provides various 'ust )n Time 0')T1 compilers, and each wor"s on a
different architecture depends on perating -ystems, that means the same Microsoft
)ntermediate /anguage 0M-)/1 can be e+ecuted on different perating -ystems. )n the following
section you can see how %ommon /anguage 2untime 0%/21 functions .
The %ommon /anguage 2untime 0%/21 is an E+ecution Environment. )t wor"s as a layer
between perating -ystems and the applications written in .Net languages that conforms to the
%ommon /anguage -pecification 0%/-1. The main function of %ommon /anguage 2untime
0%/21 is to convert the Managed %ode into native code and then e+ecute the $rogram. The
Managed %ode compiled only when it needed, that is it converts the appropriate instructions
when each function is called . The %ommon /anguage 2untime 0%/21 6s 'ust )n Time 0')T1
compilation converts )ntermediate /anguage 0M-)/1 to native code on demand at application run
time.
,uring the e+ecution of the program ,the %ommon /anguage 2untime 0%/21 manages memory,
Thread e+ecution, 7arbage %ollection 07%1 , E+ception 8andling, %ommon Type -ystem 0%T-1,
code safety verifications, and other system services. The %/2 0%ommon /anguage 2untime 1
defines the %ommon Type -ystem 0%T-1, which is a standard type system used by all .Net
languages . That means all .NET programming languages uses the same representation for
common ,ata Types , so %ommon /anguage 2untime 0%/21 is a language.independent runtime
environment. The %ommon /anguage 2untime 0%/21 environment is also referred to as a
managed environment, because during the e+ecution of a program it also controls the interaction
with the perating -ystem. )n the coming section you can see what are the main functions of
%ommon /anguage 2untime 0%/21.
The %ommon /anguage 2untime 0%/21 is a an E+ecution Environment . %ommon /anguage
2untime 0%/216s main tas"s are to convert the .NET Managed %ode to native code, manage
running code li"e a Virtual Machine and also controls the interaction with the perating -ystem.
%ommon /anguage 2untime 0%/21 manages Thread e+ecutions, Memory Management that is
allocation of b9ects and Buffers , 7arbage %ollection 07%1 . %lean up the unused b9ects and
buffers , E+ception 8andling, %ommon Type -ystem 0%T-1 that is all .NET language that
conforms to the %ommon /anguage -pecification 0%/-1 have the same primitive ,ata Types,
%ode safety verifications . code can be verified to ensure type safety, /anguage integration that
is %ommon /anguage 2untime 0%/21 follow a set of specification called %ommon /anguage
-pecification 0%/-1 , this will ensure the interoperability between languages, )ntegrated security
and other system services.
The .Net !ramewor" class library 0!%/1 provides the core functionality of .Net !ramewor"
architecture . The .Net !ramewor" %lass /ibrary 0!%/1 includes a huge collection of reusable
classes , interfaces, and value types that e+pedite and optimi:e the development process and
provide access to system functionality.
The .Net !ramewor" class library 0!%/1 organi:ed in a hierarchical tree structure and it is
divided into Namespaces. Namespaces is a logical grouping of types for the purpose of
identification. !ramewor" class library 0!%/1 provides the consistent base types that are used
across all .NET enabled languages. The %lasses are accessed by namespaces, which reside within
#ssemblies. The -ystem Namespace is the root for types in the .NET !ramewor". The .Net
!ramewor" class library 0!%/1 classes are managed classes that provide access to -ystem
-ervices . The .Net !ramewor" class library 0!%/1 classes are ob9ect oriented and easy to use in
program developments. Moreover, third.party components can integrate with the classes in
the .NET !ramewor".
%ommon /anguage -pecification 0%/-1 is a set of basic language features that .Net /anguages
needed to develop #pplications and -ervices , which are compatible with the .Net !ramewor".
When there is a situation to communicate b9ects written in different .Net %omplaint languages ,
those ob9ects must e+pose the features that are common to all the languages . %ommon /anguage
-pecification 0%/-1 ensures complete interoperability among applications, regardless of the
language used to create the application.
%ommon /anguage -pecification 0%/-1 defines a subset of %ommon Type -ystem 0%T-1 .
%ommon Type -ystem 0%T-1 describes a set of types that can use different .Net languages have
in common , which ensure that ob9ects written in different languages can interact with each other.
Most of the members defined by types in the .NET !ramewor" %lass /ibrary 0!%/1 are
%ommon /anguage -pecification 0%/-1 compliant Types. Moreover %ommon /anguage
-pecification 0%/-1 standardi:ed by E%M# .
%ommon Type -ystem 0%T-1 describes a set of types that can be used in different .Net languages
in common . That is , the %ommon Type -ystem 0%T-1 ensure that ob9ects written in different
.Net languages can interact with each other. !or %ommunicating between programs written in
any .NET complaint language, the types have to be compatible on the basic level .
These types can be Value Types or 2eference Types . The Value Types are passed by values and
stored in the stac". The 2eference Types are passed by references and stored in the heap.
%ommon Type -ystem 0%T-1 provides base set of ,ata Types which is responsible for cross
language integration. The %ommon /anguage 2untime 0%/21 can load and e+ecute the source
code written in any .Net language, only if the type is described in the %ommon Type -ystem
0%T-1 .Most of the members defined by types in the .NET !ramewor" %lass /ibrary 0!%/1 are
%ommon /anguage -pecification 0%/-1 compliant Types.
M-)/ stands for Microsoft )ntermediate /anguage. We can call it as )ntermediate /anguage 0)/1
or %ommon )ntermediate /anguage 0%)/1. ,uring the compile time , the compiler convert the
source code into Microsoft )ntermediate /anguage 0M-)/1 .Microsoft )ntermediate /anguage
0M-)/1 is a %$3.independent set of instructions that can be efficiently converted to the native
code. ,uring the runtime the %ommon /anguage 2untime 0%/216s 'ust )n Time 0')T1 compiler
converts the Microsoft )ntermediate /anguage 0M-)/1 code into native code to the perating
-ystem.
When a compiler produces Microsoft )ntermediate /anguage 0M-)/1, it also produces Metadata.
The Microsoft )ntermediate /anguage 0M-)/1 and Metadata are contained in a portable
e+ecutable 0$E1 file . Microsoft )ntermediate /anguage 0M-)/1 includes instructions for loading,
storing, initiali:ing, and calling methods on ob9ects, as well as instructions for arithmetic and
logical operations, control flow, direct memory access, e+ception handling, and other operations
The $ortable E+ecutable 0$E1 format is a file format for e+ecutables, ob9ect code, and ,//s,
used in 45.bit and ;<.bit versions of Windows operating systems.
The $E file format was defined to provide the best way for the Windows perating -ystem to
e+ecute code and also to store the essential data which is needed to run a program. $ortable
E+ecutable !ile !ormat is derived from the Microsoft %ommon b9ect !ile !ormat 0%!!1.
The .Net languages , which is conforms to the %ommon /anguage -pecification 0%/-1, uses its
corresponding runtime to run the application on different perating -ystems . ,uring the code
e+ecution time, the Managed %ode compiled only when it is needed, that is it converts the
appropriate instructions to the native code for e+ecution 9ust before when each function is called.
This process is called 'ust )n Time 0')T1 compilation, also "nown as ,ynamic Translation . With
the help of 'ust )n Time %ompiler 0')T1 the %ommon /anguage 2untime 0%/21 doing these
tas"s.
The %ommon /anguage 2untime 0%/21 provides various 'ust )n Time compilers 0')T1 and each
wor"s on a different architecture depending on perating -ystem. That is why the same
Microsoft )ntermediate /anguage 0M-)/1 can be e+ecuted on different perating -ystems
without rewrite the source code. 'ust )n Time 0')T1 compilation preserves memory and save time
during application initiali:ation. 'ust )n Time 0')T1 compilation is used to run at high speed, after
an initial phase of slow interpretation. 'ust )n Time %ompiler 0')T1 code generally offers far
better performance than interpreters.
Managed %ode in Microsoft .Net !ramewor", is the code that has e+ecuted by the %ommon
/anguage 2untime 0%/21 environment. n the other hand 3nmanaged %ode is directly e+ecuted
by the computer6s %$3. ,ata types, error.handling mechanisms, creation and destruction rules,
and design guidelines vary between managed and unmanaged ob9ect models.
The benefits of Managed %ode include programmers convenience and enhanced security .
Managed code is designed to be more reliable and robust than unmanaged code , e+amples are
7arbage %ollection , Type -afety etc. The Managed %ode running in a %ommon /anguage
2untime 0%/21 cannot be accessed outside the runtime environment as well as cannot call
directly from outside the runtime environment. This ma"es the programs more isolated and at the
same time computers are more secure . 3nmanaged %ode can bypass the .NET !ramewor" and
ma"e direct calls to the perating -ystem. %alling unmanaged code presents a ma9or security
ris".
Metadata in .Net is binary information which describes the characteristics of a resource . This
information include ,escription of the #ssembly , ,ata Types and members with their
declarations and implementations, references to other types and members , -ecurity permissions
etc. # module6s metadata contains everything that needed to interact with another module.
,uring the compile time Metadata created with Microsoft )ntermediate /anguage 0M-)/1 and
stored in a file called a Manifest . Both Metadata and Microsoft )ntermediate /anguage 0M-)/1
together wrapped in a $ortable E+ecutable 0$E1 file. ,uring the runtime of a program 'ust )n
Time 0')T1 compiler of the %ommon /anguage 2untime 0%/21 uses the Metadata and converts
Microsoft )ntermediate /anguage 0M-)/1 into native code. When code is e+ecuted, the runtime
loads metadata into memory and references it to discover information about your code6s classes,
members, inheritance, and so on. Moreover Metadata eliminating the need for )nterface
,efinition /anguage 0),/1 files, header files, or any e+ternal method of component reference.
Microsoft .Net #ssembly is a logical unit of code, it contains code that the %ommon /anguage
2untime 0%/21 e+ecutes. #ssembly is really a collection of types and resource information that
are built to wor" together and form a logical unit of functionality. ,uring the compile time
Metadata is created, with Microsoft )ntermediate /anguage 0M-)/1, and stored in a file called a
Manifest . Both Metadata and Microsoft )ntermediate /anguage 0M-)/1 together wrapped in a
$ortable E+ecutable 0$E1 file. Manifest contains information about itself. This information is
called #ssembly Manifest, it contains information about the members, types, references and all
the other data that the runtime needs for e+ecution.
Every #ssembly you create contains one or more program files and a Manifest. There are two
types program files = $rocess #ssemblies 0E>E1 and /ibrary #ssemblies 0,//1. Each #ssembly
can have only one entry point 0that is, ,llMain, WinMain, or Main1. We can create two types of
#ssembly, private #ssembly and shared #ssembly . # private #ssembly is used only by a single
application, and usually it is stored in that application6s install directory. # shared #ssembly is
one that can be referenced by more than one application. )f multiple applications need to access
an #ssembly, we should add the #ssembly to the 7lobal #ssembly %ache 07#%1.
#n #ssembly Manifest is a file that containing Metadata about .NET #ssemblies. #ssembly
Manifest contains a collection of data that describes how the elements in the assembly relate to
each other. )t describes the relationship and dependencies of the components in the #ssembly,
versioning information, scope information and the security permissions re*uired by the
#ssembly.
The #ssembly Manifest can be stored in $ortable E+ecutable 0$E1 file with Microsoft
)ntermediate /anguage 0M-)/1 code. ?ou can add or change some information in the #ssembly
Manifest by using assembly attributes in your code. The #ssembly Manifest can be stored in
either a $E file 0an .e+e or .dll1 with Microsoft )ntermediate /anguage 0M-)/1 code or in a
standalone $E file that contains only assembly manifest information. 3sing )/,asm, you can
view the manifest information for any managed ,//.
Each computer on which the %ommon /anguage 2untime is installed has a machine.wide code
cache called the 67lobal #ssembly %ache6. The 7lobal #ssembly %ache 07#%1 enables you to
share assemblies across numerous applications.
The 7#% is automatically installed with the .NET runtime. The global assembly cache is located
in 6Windows@WinNT6 directory and inherits the directory6s access control list that administrators
have used to protect the folder.
The approach of having a specially controlled central repository addresses the shared library
concept and helps to avoid pitfalls of other solutions that lead to drawbac"s li"e ,// hell.
The 7lobal #ssembly %ache Tool 07acutil.e+e1, that allows you to view and manipulate the
contents of the 7lobal #ssembly %ache.
# .NET !ramewor" assembly containing resources specific to a given language. 3sing satellite
assemblies, you can place the resources for different languages in different assemblies, and the
correct assembly is loaded into memory only if the user selects to view the application in that
language. )n general, assemblies should contain culture.neutral resources. )f you want to locali:e
your assembly 0for e+ample use different strings for different locales1 you should use satellite
assemblies.
3se the #ssembly /in"er 0#l.e+e1 to compile .resources files into satellite assemblies. #l.e+e
creates an assembly from the .resources files that you specify. By definition, satellite assemblies
can only contain resources. They cannot contain any e+ecutable code.
# .NET static assembly can consist of following elements=
a1 #ssembly Manifest . The Metadata that describes the assembly and its contents
b1 Type Metadata . ,efines all types, their properties and methods.
c1 M-)/ . Microsoft intermediate language
d1 # set of 2esources . #ll other resources li"e icons, images etc.
nly the assembly manifest is re*uired, but either types or resources are needed to give the
assembly in any meaningful functionality.
# private assembly is an assembly that is available to particular application where they are "ept,
and a -hared #ssembly is a public assembly that is shared by multiple applications. That means,
a $rivate #ssembly cannot be references outside the scope of the folder where they are "ept and
a -hared #ssembly is one that can be referenced by more than one application.
)n order to share an assembly, the assembly must be e+plicitly built for this purpose by giving it a
cryptographically strong name . By contrast, a private assembly name need only be uni*ue
within the application that uses it.
The classes that ship with the .NET !ramewor" are all built as shared assemblies.
-trong name consists of an #ssemblys identity, that means the #ssemblies can be assigned a
cryptographic signature. The strong name guarantees the integrity of the assembly which
prevents someone from ta"ing over the name of the assembly.
-trong Name includes the name of the .net assembly, version number, culture identity, and a
public "ey to"en. )t is generated from an assembly file using the corresponding private "ey.
-trong names guarantee name uni*ueness by relying on uni*ue "ey pairs.
To create a "ey pair
#t the command prompt, type the following command=
sn ." fileName
)n this command, file name is the name of the output file containing the "ey pair.
Namespaces are the way to organi:e .NET !ramewor" %lass /ibrary into a logical grouping
according to their functionality, usability as well as category they should belong to, or we can say
Namespaces are logical grouping of types for the purpose of identification.
The .NET !ramewor" %lass /ibrary 0!%/ 1 is a large collection of thousands of %lasses. These
%lasses are organi:ed in a hierarchical tree. The -ystem Namespaces is the root for types in
the .NET !ramewor". We can uni*uely identify any %lass in the .NET !ramewor" %lass /ibrary
0!%/ 1 by using the full Namespaces of the class .)n .Net languages every program is created
with a default Namespaces . $rogrammers can also create their own Namespaces in .Net
languages.
#n application domain is a virtual process and is used to isolate applications from one another.
Each application domain has their own virtual address space which scopes the resources for the
application domain using that address space.
Each application running within its main process boundaries and its application domain
boundaries. #ll ob9ects created within the same application scope are created within the same
application domain. Multiple application domains can e+ist in a single operating system process.
#n application running inside one application domain cannot directly access the code running
inside another application domain.
-ystem.#pp,omain is the main class you can use to deal with application domains.
The .NET -ecurity Model provides code access permissions and code identity permissions. %ode
#ccess -ecurity is the part of the .NET security model that determines whether or not the code is
allowed to run, and what resources it can use when it is running. %ode #ccess -ecurity policy
uses evidence to help grant the right permissions to the right assembly.
#n administrator can configure %ode #ccess -ecurity policy to restrict the resource types that
code can access and the other privileged operations it can perform. %ode #ccess -ecurity allows
code to be trusted to varying degrees depending on where the code originates and on other
aspects of the code6s identity. %ode #ccess -ecurity can also help minimi:e the damage that can
result from security vulnerabilities in your code.
The .Net !ramewor" provides a new mechanism for releasing unreferenced ob9ects from the
memory 0that is we no longer needed that ob9ects in the program1 ,this process is called 7arbage
%ollection 07%1. When a program creates an b9ect, the b9ect ta"es up the memory. /ater
when the program has no more references to that b9ect, the b9ect6s memory becomes
unreachable, but it is not immediately freed. The 7arbage %ollection chec"s to see if there are
any b9ects in the heap that are no longer being used by the application. )f such b9ects e+ist,
then the memory used by these b9ects can be reclaimed. -o these unreferenced b9ects should
be removed from memory , then the other new b9ects you create can find a place in the 8eap.
The reclaimed b9ects have to be !inali:ed later. !inali:ation allows a resource to clean up after
itself when it is being collected. This releasing of unreferenced b9ects is happening
automatically in .Net languages by the 7arbage %ollector 07%1. The programming languages
li"e %((, programmers are responsible for allocating memory for b9ects they created in the
application and reclaiming the memory when that b9ect is no longer needed for the program.
)n .Net languages there is a facility that we can call 7arbage %ollector 07%1 e+plicitly in the
program by calling -ystem.7%.%ollect.
Thread in computer science means a se*uence of e+ecution instructions that can run
independently , that is a single flow of e+ecution in a process. Thread is li"e a process, at least
one thread e+ists within each process. -ingle Thread 0normal programs1 in computer science
means that only one tas" can e+ecute and at the same time the other tas"s have to wait for the
completion of the current tas" li"e in a *ueue. -ingle thread resulted in systems idle time and
application performance.
Multithreading allows multiple process to e+ecute concurrently within a single program .That is
more than one tas" in a program can e+ecute at the same time and each thread run independently
of its own. )f multiple threads can e+ist within a process, typically share the state information of
a process, and share memory and other resources directly. Each thread maintains e+ception
handlers, a scheduling priority, and a set of structures the system uses to save the thread conte+t
until it is scheduled.
)n multiple threaded programming we can use system6s idle time, so it leads improved
application performance . #lso we can set priority in each Threads . Threads with higher priority
are e+ecuted in preference to threads with lower priority. )t is recommended that you use as few
threads as possible, thereby minimi:ing the use of perating -ystem resources . %hec" the
following lin"s to see how Multi Threaded applications wor"s in VB.NET .
A. Multithreaded -oc"et $rogramming
5. Multi Threaded %hat -erver $rogram
DATATYPE in a programming language describes that what type of data a variable can hold.
When we declare a variable, we have to tell the compiler about what type of the data the variable
can hold or which data type the variable belongs to.
Syntax : ,im VariableName as ,ataType
VariableName : the variable we declare for hold the values.
DataType : The type of data that the variable can hold
VB.NET sample :
Dim count As Integer
count : is the variable name
Integer : is the data type
The above e+ample shows , declare a variable 6count6 for holding integer values.
)n the variable count we can hold the integer values in
the range of .5,A<B,<C4,;<C to (5,A<B,<C4,;<B.
The follwing are the some of commonly using datatypes in vb.net.
Boolean
Boolean variables are stored A; bit numbers and it can hold only True or false.
VB.NET Runtime type : ystem.Boolean
VB.NET declaration : dim chec! as Boolean
VB.NET Initiali"ation : chec! # $alse
VB.NET de$ault initiali"ation value : $alse
Inteer
Inteer variables are stored sighned 45 bit integer values in the range of .5,A<B,<C4,;<C to
(5,A<B,<C4,;<B
VB.NET Runtime type : ystem.Int%&
VB.NET declaration : dim count as Integer
VB.NET Initiali"ation : count # '((
VB.NET de$ault initiali"ation value : (
Strin
Strin variables are stored any number of alphabetic, numerical, and special characters . )ts
range from D to appro+imately 5 billion 3nicode characters.
VB.NET Runtime type : ystem.tring
VB.NET declaration : Dim str As tring
VB.NET Initiali"ation : str # )tring Test)
VB.NET de$ault initiali"ation value : Nothing
)n VisualBasic.Net we can convert a datatype in two ways. Implicit !on"ersion and Explicit
con"ersion . #lso we can convert a type value to a reference and reference value to a type value.
These are called Boxin and unBoxin . Bo+ing referes value type to reference type and
unbo+ing , reference type ot value type.
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im chec" #s Boolean
chec" F True
MsgBo+0GThe value assigned for chec" is = G H chec"1
,im count #s )nteger
count F ADD
MsgBo+0GThe value holding count is = G H count1
,im str #s -tring
str F G-tring test G
MsgBo+0GThe value holding str is = G H str1
End -ub
End %lass
When you e+ecute this programme , you will get GtrueG in the first message bo+ and , ADD in the
second message bo+ and G-tring TestG in the last message bo+.
Implicit Type !on"ersions
Implicit !on"ersion perform automatically in VB.NET, that is the compiler is ta"ing care of the
conversion.
The following e+ample you can see how it happen.
'. Dim iDbl As Double
&. Dim iInt As Integer
%. iDbl # *.'&%
+. ,sgBo-.)The value o$ iDbl is ) iDbl/
0. iInt # iDbl
1. ,sgBo-.)The value o$ iInt is ) iInt/
line no A = ,eclare a ,ouble datatype variable i,ble
line no 5 = ,eclare an )nteger datatyoe variable i)nt
line no 4 = #ssign a decimal value to i,bl
line no < = ,isplay the value of i,bl
line no I = #ssign the value of i,bl to i)nt
line no ; = ,isplay the value of i)nt
The first messagebo+ display the value of i,bl is J.A54
The second messegebo+ display the value od i)nt is J
i)nt display only J because the value is narrowed to J to fit in an )nteger variable.
8ere the %ompiler made the conversion for us. These type fo conversions are called Implicit
!on"ersion .
The )mplicit %onversion perform only when the #ption Strict s$itc% is #&&
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im i,bl #s ,ouble
,im i)nt #s )nteger
i,bl F J.A54
MsgBo+0GThe value of i,bl is G H i,bl1
i)nt F i,bl
6after conversion
MsgBo+0GThe value of i)nt is G H i)nt1
End -ub
End %lass
Explicit Type !on"ersions
)n some cases we have to perform conversions , that is the compiler does not automatically
convert a type to another . These type of conversion is called Explicit con"ersion . #n e+plicit
conversion uses a type conversion "eyword. With these conversion "eywords we hav to perform
the E+plicit %onversion.
AccessSpeci'iers describes as the scope of accessibility of an b9ect and its members. We can
control the scope of the member ob9ect of a class using access specifiers. We are using access
specifiers for providing security of our applications.
Visual Basic .Net provide five access specifiers , they are as follows =
2ublic3 2rivate 3 2rotected 3 4riend and 2rotected4riend .
Public :
$ublic is the most common access specifier. )t can be access from anywhere, hat means there is
no restriction on accessability. The scope of the accessibility is inside class also in outside the
class.
Pri"ate :
The scope of the accessibility is limited only inside the classes in which they are decleared. The
$rivate members can not be accessed outside the class and it is the least permissive access level.
Protected :
The scope of accessibility is limited within the class and the classes derived 0)nherited 1from this
class.
&riend :
The !riend access specifier can access within the program that contain its declarations and also
access within the same assembly level. ?ou can use friend instead of ,im "eyword.
Protected &riend:
$rotected!riend is same access lebels of both $rotected and !riend. )t can access anywhere in the
same assebly and in the same class also the classes inherited from the same class .
Exceptions are the occurrence of some condition that changes the normal flow of e+ecution . !or
e+= you programme run out of memory , file does not e+ist in the given path , networ"
connections are dropped etc. More specifically for better understanding, we can say it as
(untime Errors .
)n .NET languages, Structured Exceptions handling is a fundamental part of !ommon
)anuae (untime. )t has a number of advantages over the 5n Error statements provided in
previous versions of Visual Basic. #ll e+ceptions in the %ommon /anguage 2untime are derived
from a single base class , also you can create your own custom E+ception classes. ?ou can create
an E+ception class that inherits from E+ception class .
?ou can handle E+ceptions using Try..6atch statement.
Try
code
exit 'rom Try
!atc% *Exception *As Type++
code , i' t%e exception occurred t%is code $ill execute
exit 'rom !atc%
&inally
The code in the $inally bloc" will e+ecute even if there is no E+ceptions. That means if you write
a finally bloc" , the code should e+ecute after the e+ecution of try bloc" or catch bloc".
Try
code
exit 'rom Try
!atc% *Exception *As Type++
code , i' t%e exception occurred t%is code $ill execute
exit !atc%
&inally
code , t%is code s%ould execute - i' exception occurred or not
!rom the following VB.NET code , you can understand how to use try..catch statements. 8ere
we are going to divide a number by :ero .
-ource code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
Try
,im i #s )nteger
,im resultValue #s )nteger
i F ADD
resultValue F i @ D
MsgBo+0GThe result is G H resultValue1
%atch e+ #s E+ception
MsgBo+0GE+ception catch here ..G1
!inally
MsgBo+0G!inally bloc" e+ecuted G1
End Try
End -ub
When you e+ecute this program you will )E-ception catch here ..) first and then )4inally
bloc! e-ecuted ) . That is when you e+ecute this code , an e+ception happen and it will go to
catch bloc" and then it will go to finally bloc".
#ption Explicit statement ensures whether the compiler re*uires all variables to be e+plicitly
declared or not before it use in the program.
5ption E-plicit 75n 5$$8
The #ption Explicit has two modes. #n and #'' mode. )f ption E+plicit mode in N , you
have to declare all the variable before you use it in the program . )f not , it will generate a
compile.time error whenever a variable that has not been declared is encountered .)f the ption
E+plicit mode is !! , Vb.Net automatically create a variable whenever it sees a variable
without proper declaration.
By default the 5ption E-plicit is 5n
With the ption E+plicit n , you can reduce the possible errors that result from misspelled
variable names. Because in ption E+plicit n mode you have to declare each variable in the
program for storing data.
Ta"e a loo" at the following programs, it will give you a clear picture of ption E+plicit.
The following program is a normal vb.net program , so the default mode of ption E+plicit n is
using. The default is ption E+plicit n , so we do not need to put it in the source code.
VB.NET Source !ode
Public !lass &orm.
Pri"ate Sub Button./!lic01ByVal sender As System.#b2ect- /
ByVal e As System.E"entArs3 4andles Button..!lic0
Dim someVariable As Strin
someVariable 5 6#ption Explicit #N6
7sBox1someVariable3
End Sub
End !lass
The above program , declare a -tring variable and assigned a value in it and it displays.
Ta"e a loo" at the following program , it is an e+ample of 5ption E-plicit 5$
8ere GsomeVariableG is not declared , because the 5ption E-plicit 5$ , without any compiler
error you can continue the program.
#ption Strict is prevents program from automatic variable conversions, that is implicit data type
conversions .
5ption trict 75n 5$$8
By default 5ption trict is 5$$
!rom the following e+ample you can understand the use of ption -trict.
VB.NET Source !ode
Public !lass &orm.
Pri"ate Sub Button./!lic01ByVal sender As System.#b2ect- /
ByVal e As System.E"entArs3 4andles Button..!lic0
Dim lonNum As )on
Dim intNum As Inteer
lonNum 5 .89:;
intNum 5 lonNum
7sBox1intNum3
End Sub
End !lass
The above program is a normal vb.net program and is in default 5ption trict 5$$ . Because its
ption -trict ff we can convert the value of /ong to an )nteger.
When you write this source code the compiler will shows the message
)5ption trict 5n disallo9s implicit conversions $rom :;ong: to :Integer:)
The compiler generate error because in the program we put )5ption trict 5n) and prevent the
program from automatic conversion.
#n Error <oTo statements is an e+ample of Vb.Net6s =nstructured Exception 4andlin .
VB.NET has two types of E+ception handling . Structured Error 4andlin and =nstructured
Error %andlin . VB.NET using Try..6atch statement for -tructured Error handling and n
Error 7oTo statement is using for 3nstructured Error handling.
Error <oTo redirect the flow of the program in a given location.
#n Error (esume Next . whenever an error occurred in runtime , s"ip the statement and
continue e+ecution on following statements.
Ta"e a loo" at the following program
VB.NET Source !ode
Public !lass &orm.
Pri"ate Sub Button./!lic01ByVal sender As System.#b2ect- /
ByVal e As System.E"entArs3 4andles Button..!lic0
Dim result As Inteer
Dim num As Inteer
num 5 .>>
result 5 num ? >
7sBox16%ere63
End Sub
End !lass
when u e+ecute this program you will get error message li"e G Arithmetic operation resulted in
an over$lo9 G
-ee the program we put an 5n Error <oTo statement
When you e+ecute the program you will get the message bo+ G%ontrol 8ereG . Because the n
Error statement redirect the e+ception to the /abel statement.
The conditional statement I& E)SE , is use for e+amining the conditions that we provided, and
ma"ing decision based on that contition. The conditional statement e+amining the data using
comparison operators as well as logical operators.

I' *your condition %ere+
Your code %ere
Else
Your code 4ere
End I'
)f the contition is T23E then the control goes to between )! and Else bloc" , that is the program
will e+ecute the code between )! and E/-E statements.
)f the contition is !/#-E then the control goes to between E/-E and EN, )! bloc" , that is the
program will e+ecute the code between E/-E and EN, )! statements.
)f you want o chec" more than one condition at the same time , you can use Else)f .

I' *your condition %ere+
Your code %ere
ElseI' *your condition %ere+
Your code %ere
ElseI' *your condition %ere+
Your code %ere
Else
Your code 4ere
End I'
'ust ta"e a real.time e+ample . When we want to analy:e a mar" lists we have to apply some
conditions for grading students depends on the mar"s.
!ollowing are the garding rule of the mar" list=
A1 )f the mar"s is greater than CD then the student get higher first class
51 )f the mar"s less than CD and greater than ;D then the student get first class
41 )f the mar"s less than ;D and greater than <D then the student get second class
<1 The last condition is , if the mar"s less than <D then the student fail.
Now here implementing these conditions in a VB.NET program.

.. I' total7ar0s @5 A> T%en
8. 7sBox16<ot 4i%er &irst !lass 63
9. ElseI' total7ar0s @5 B> T%en
:. 7sBox16<ot &irst !lass 63
;. ElseI' total7ar0s @5 :> T%en
B. 7sBox16Cust pass only63
D. Else
A. 7sBox16&ailed63
E. End I'
/ine A = %hec"ing the total mar"s greaterthan or e*ual to CD
/ine 5 = )f total mar"s greater than CD show message . G7ot 8igher !irst %lass G
/ine 4 = %hec"ing the total mar"s greaterthan or e*ual to ;D
/ine < = )f total mar"s greater than ;D show message . G7ot !irst %lass G
/ine I = %hec"ing the total mar"s greaterthan or e*ual to <D
/ine ; = )f total mar"s greater than <D show message . G'ust pass onlyG
/ine B = )f those three conditions failed program go to the ne+t coding bloc"
/ine C = )f all fail shows message G!ailedG
/ine J = Ending the condition bloc"
VB.NET Source !ode
Public !lass &orm.
Pri"ate Sub Button./!lic01ByVal sender As System.#b2ect-
ByVal e As System.E"entArs3 4andles Button..!lic0
Dim total7ar0s As Inteer
total7ar0s 5 ;E
I' total7ar0s @5 A> T%en
7sBox16<or 4i%er &irst !lass 63
ElseI' total7ar0s @5 B> T%en
7sBox16<or &irst !lass 63
ElseI' total7ar0s @5 :> T%en
7sBox16Cust pass only63
Else
7sBox16&ailed63
End I'
End Sub
End !lass
)n this e+ample the total mar"s is IJ , when you e+ecute this program you will get in
messagebo+ G'ust $ass nlyG
)f you want to chec" a condition within condition you can use nested if statements

I' *your condition %ere+
I' *your condition %ere+
Your code %ere
Else
Your code 4ere
End I'
Else
Your code 4ere
End I'
#lso you can write )! E/-E -tatements in a single line
I$ 7your condition here8 76ode8 Else 7code8
When you e+ecute this program you will get in messagebo+ G!ailed G
Whenever you face a situation in programming to repeat a tas" for several times 0more than one
times 1 or you have to repeat a tas" till you reach a condtition, in these situations you can use
loop statements to achieve your desired results.
!2 NE>T /oop, !2 E#%8 /oop , W8)/E /oop and , W8)/E /oop are the %ommonly
used loops in Visual Basic.NET 5DDI 0 VB.NET 5DDI1 .
&#( NEFT /oop =
The &#( NEFT /oop , e+ecute the loop body 0the source code within !or ..Ne+t code bloc"1 to
a fi+ed number of times.

&or "ar5*startValue+ To *endValue+ *Step+
*loopBody+
Next *"ar+
var = The counter for the loop to repeat the steps.
starValue = The starting value assign to counter variable .
endValue = When the counter variable reach end value the /oop will stop .
loopBody = The source code between loop body
/ets ta"e a simple real time e+ample , )f you want to show a messagebo+ I times and each time
you want to see how many times the message bo+ shows.

.. startVal5.
8. endVal 5 ;
9. &or "ar 5 startVal To endVal
:. s%o$ messae
;. Next "ar
/ine A= /oop starts value from A
/ine 5= /oop will end when it reach I
/ine 4= #ssign the starting value to var and inform to stop when the var reach endVal
/ine <= E+ecute the loop body
/ine I= Ta"ing ne+t step , if the counter not reach the endVal
VB.NET Source !ode

Public !lass &orm.
Pri"ate Sub Button./!lic01ByVal sender As System.#b2ect-
ByVal e As System.E"entArs3 4andles Button..!lic0
Dim "ar As Inteer
Dim startVal As Inteer
Dim endVal As Inteer
startVal 5 .
endVal 5 ;
&or "ar 5 startVal To endVal
7sBox167essae Box S%o$s 6 G "ar G 6 Times 63
Next "ar
End Sub
End !lass
When you e+ecute this program , )t will show messagebo+ five time and each time it shows the
counter value.
)f you want to Exit from !2 NE>T /oop even before completing the loop Visual Basic.NET
provides a "eyword Exit to use within the loop body.

&or "ar5startValue To endValue *Step+
*loopBody+
!ontition
*Exit &or+
Next *"ar+
-ource code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im var #s )nteger
,im startVal #s )nteger
,im endVal #s )nteger
startVal F A
endVal F I
!or var F startVal To endVal
MsgBo+0GMessage Bo+ -hows G var G Times G1
)f var F 4 Then
E+it !or
End )f
Ne+t var
End -ub
End %lass
When you e+ecute the above source code , the program shows the message bo+ only three times .
Whenever you face a situation in programming to repeat a tas" for several times 0more than one
times 1 or you have to repeat a tas" till you reach a condition, in these situations you can use loop
statements to achieve your desired results.
!2 NE>T /oop, !2 E#%8 /oop , W8)/E /oop and , W8)/E /oop are the %ommonly
used loops in Visual Basic.NET 5DDI 0 VB.NET 5DDI1 .
&or Eac% )oop
!2 E#%8 /oop usually using when you are in a situation to e+ecute every single element or
item in a group 0li"e every single element in an #rray, or every single files in a folder or , every
character in a -tring 1 , in these type of situation you can use !or Each loop.

&or Eac% *Item+ In *<roup+
*loopBody+
Next *Item+
)tem = The )tem in the group
7roup = The group containing items
/oopBody = The code you want to e+ecute within !or Each /oop
/et6s ta"e a real time e+ample , if you want to display the each character in the website name
G8TT$=@@NET.)N!2M#T)N-.%MG , it is convenient to use !or Each /oop.

.. siteName 5 64TTP:??NET,IN&#(7ATI#NS.!#76
8. &or Eac% sinle!%ar In siteName
9. 7sBox1sinle!%ar3
:. Next
/ine A= #ssigning the site name in a variable
/ine 5= This line is e+tracting the single item from the group
/ine 4= /oop body
/ine <= Ta"ing the ne+t step
-ource code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im siteName #s -tring
,im single%har #s %har
siteName F G8TT$=@@NET.)N!2M#T)N-.%MG
!or Each single%har )n siteName
MsgBo+0single%har1
Ne+t
End -ub
End %lass
When you e+ecute this program you will get each character of the string in Messagebo+.
Whenever you face a situation in programming to repeat a tas" for several times 0more than one
times 1 or you have to repeat a tas" till you reach a condition, in these situations you can use loop
statements to achieve your desired results.
!2 NE>T /oop, !2 E#%8 /oop , W8)/E /oop and , W8)/E /oop are the %ommonly
used loops in Visual Basic.NET 5DDI 0 VB.NET 5DDI1 .
H%ile ..End H%ile
While .. End While /oop e+ecute the code body 0the source code within While and End while
statements 1 until it meets the specified condition.

H%ile *condition+
*loop body+
End H%ile
%ondition = The condition set by the user

.. counter 5 .
8. H%ile 1counter I5 .>3
9. 7essae
:. counter 5 counter J .
;. End H%ile
/ine A= %ounter start from A
/ine 5= While loop chec"ing the counter if it is less than or e*ual to AD
/ine 4= Each time the /oop e+ecute the message and show
/ine <= %ounter increment the value of A each time the loop e+ecute
/ine I= End of the While End While /oop body
-ource code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im counter #s )nteger
counter F A
While 0counter KF AD1
MsgBo+0G%ounter Now is = G counter1
counter F counter ( A
End While
End -ub
End %lass
When you e+ecute the program AD times the message shows with counter and e+it from the
While .. End While loop.
IDE
Visual -tudio is a powerful and customi:able programming environment that contains all the
tools you need to build programs *uic"ly and efficiently. )t offers a set of tools that help you
write and modify the code for your programs, and also detect and correct errors in your
programs.
Before you start learning more about VB.NET programming, it is important to understand the
development environment and identify some of the fre*uently using programming tools in Visual
-tudio ),E
.. 7enu Bar
8. Standard Toolbar
9. Tool Box
:. &orms Desiner
;. #utput Hindo$
B. Solution Explorer
D. Properties Hindo$
Visual Basic.NET ),E is built out of a collection of different windows. -ome windows are used
for writing code, some for designing interfaces, and others for getting a general overview of files
or classes in your application.
Visual -tudio organi:es your wor" in pro9ects and solutions. # solution can contain more than
one pro9ect, such as a ,// and an e+ecutable that references that ,//. !rom the following
chapters you will learn how to use these Visual -tudio features for your programming needs.
HIND#HS &#(7S
VB.Net programmers have made e+tensive use of forms to build user interfaces. Each time you
create a Windows application, Visual -tudio will display a default blan" form, onto which you
can drag and drop controls from the Visual -tudio Toolbo+ window.
The first 9ob is to start a new pro9ect and build a form. pen your Visual -tudio and select !ile.
LNew$ro9ect and select Visual Basic from the New pro9ect dialog bo+ and select Windows
!roms #pplication. Enter a pro9ect name and clic" M button. The following picture shows how
to crate a new !orm in Visual -tudio.
-elect pro9ect type from New pro9ect dialog Bo+
When you add a Windows !orm to your pro9ect, many of the forms properties are set by default.
#lthough these values are convenient, they will not always suit your programming needs. The
following picture shows how is the default !orm loo" li"e.
#t the top of the form there is a title bar which displays the forms title. !ormA is the default
name, you can change the name to your convenience . The title bar also includes the control bo+,
which holds the minimi:e, ma+imi:e, and close buttons. )f you want to set any properties of the
!orm, you can use Visual -tudio $roperty window to change it.
!or e+ample , to change the forms title from !ormA to My!orm, clic" on !ormA and move to the
right side down $roperties window, set Te+t property to My!orm. Then you can see the Title of
the form is changed. /i"ewise you can set any properties of !orm through $roperties window.
?ou can also set the properties of the !ormA through coding.
!or e+ample , if you want to change the bac" color of the form to Brown , you can code li"e this.
7e.Bac0!olor 5 !olor.Bro$n
/i"wise you can change other properties of !ormA through coding.
The following VB.Net source code shows how to change the Title, Bac"%olor, -i:e, /ocation
and Ma+imi:eBo+ properties of !ormA. %opy and paste the following VB.Net source code to
source code editor of your Visual -tudio.
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s
-ystem.Event#rgs1 8andles MyBase./oad
Me.Te+t F G%hange $rperties Through %odingG
Me.Bac"%olor F %olor.Brown
Me.-i:e F New -i:e04ID, A5I1
Me./ocation F New $oint04DD, 4DD1
Me.Ma+imi:eBo+ F !alse
End -ub
End %lass
#=TP=T
When you e+ecute 0press !I "ey1 the program the form is loo" li"e the following image.
The Windows based programs you create using Visual Basic .NET run in the conte+t of a form.
When you close the form, the application also ends.
Microsoft Visual -tudio .NET controls are the graphical tools you use to build the user interface
of a VB.Net program. /abels are one of the most fre*uently used Visual Basic control.
)ABE)
# /abel control lets you place descriptive te+t , where the te+t does not need to be changed by
the user. The /abel class is defined in the -ystem.Windows.!orms namespace.
#dd a /abel control to the form. %lic" /abel in the Toolbo+ and drag it over the forms ,esigner
and drop it in the desired location.
)f you want to change the display te+t of the /abel, you have to set a new te+t to the Te+t
property of /abel.
)abel..Text 5 6T%is is my 'irst )abel6
?ou can load )mage in /abel control , if you want to load an )mage in the /able control you can
code li"e this
)abel..Imae 5 Imae.&rom&ile16!:Ktestimae.2p63
The following source code shows how to set some properties of the /abel through coding.
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles MyBase./oad
/abelA.Te+t F GThis is my first /abelG
/abelA.Border-tyle F Border-tyle.!i+ed-ingle
/abelA.Te+t#lign F %ontent#lignment.Middle%enter
End -ub
End %lass
TEFT B#F
VB.Net provides several mechanisms for gathering input in a program. # Te+tBo+ control is
used to display, or accept as input, a single line of te+t.
VB.Net programmers ma"e e+tensive use of the Te+tBo+ control to let the user view or enter
large amount of te+t. # te+t bo+ ob9ect is used to display te+t on a form or to get user input while
a VB.Net program is running. )n a te+t bo+, a user can type data or paste it into the control from
the clipboard.
!or displaying a te+t in a Te+tBo+ control , you can code li"e this
TextBox..Text 5 6%ttp:??"b.net,in'ormations.com6
?ou can also collect the input value from a Te+tBo+ control to a variable li"e this way
Dim "ar As Strin
"ar 5 TextBox..Text
when a program wants to prevent a user from changing the te+t that appears in a te+t bo+, the
program can set the controls 2eadonly property is to True.
TextBox..(ead#nly 5 True
By default Te+tBo+ accept single line of characters , )f you need to enter more than one line in a
Te+tBo+ control, you should change the Multiline property is to True.
TextBox..7ultiline 5 True
-ometimes you want a te+tbo+ to receive password from the user. )n order to "eep the password
confidential, you can set the $assword%har property of a te+tbo+ to a specific character.
TextBox..Pass$ord!%ar 5 6L6
The above code set the $assword%har to N , so when the user enter password then it display only
N instead of other characters.
!rom the following VB.Net source code you can see some important property settings to a
Te+tBo+ control.
%oding
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
MyBase./oad
Te+tBo+A.Width F 5DD
Te+tBo+A.8eight F ID
Te+tBo+A.Multiline F True
End -ub
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im var #s -tring
var F Te+tBo+A.Te+t
MsgBo+0var1
End -ub
End %lass
!#7B# B#F
VB.Net controls are located in the Toolbo+ of the development environment, and you use them
to create ob9ects on a form with a simple series of mouse clic"s and dragging motions. The
%omboBo+ control , which lets the user choose one of several choices.
The user can type a value in the te+t field or clic" the button to display a drop down list. )n
addition to display and selection functionality, the %omboBo+ also provides features that enable
you to efficiently add items to the %omboBo+.
!omboBox..Items.Add16Sunday63
?ou can set which item should shown while it displaying in the form for first time.
!omboBox..SelectedItem 5 !omboBox..Items193
When you run the above code it will show the forth item in the combobo+. The item inde+ is
starting from D.
)f you want to retrieve the displayed item to a string variable , you can code li"e this
Dim "ar As Strin
"ar 5 !omboBox..Text
?ou can remove items from a combobo+ in two ways. ?ou can remove item at a the specified
inde+ or giving a specified item by name.
!omboBox..Items.(emo"eAt1.3
The above code will remove the second item from the combobo+.
!omboBox..Items.(emo"e16&riday63
The above code will remove the item G!ridayG from the combobo+.
The ,rop,own-tyle property specifies whether the list is always displayed or whether the list is
displayed in a drop down. The ,rop,own-tyle property also specifies whether the te+t portion
can be edited.
!omboBox..DropDo$nStyle 5 !omboBoxStyle.DropDo$n
The following VB.Net source code add seven days in a wee" to a combo bo+ while load event of
a Windows !orm and display the fourth item in the combobo+.
Source code
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
MyBase./oad
%omboBo+A.)tems.#dd0G-undayG1
%omboBo+A.)tems.#dd0GMondayG1
%omboBo+A.)tems.#dd0GTuesdayG1
%omboBo+A.)tems.#dd0GwednesdayG1
%omboBo+A.)tems.#dd0GThursdayG1
%omboBo+A.)tems.#dd0G!ridayG1
%omboBo+A.)tems.#dd0G-aturdayG1
%omboBo+A.-elected)tem F %omboBo+A.)tems041
End -ub
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im var #s -tring
var F %omboBo+A.Te+t
MsgBo+0var1
End -ub
End %lass
)IST B#F
VB.Net provides several mechanisms for gathering input in a program. # Windows !orms
/istBo+ control displays a list of choices which the user can select from.
?ou can use the #dd or )nsert method to add items to a list bo+. The #dd method adds new items
at the end of an unsorted list bo+. The )nsert method allows you to specify where to insert the
item you are adding.
)istBox..Items.Add16Sunday63
The -electionMode property determines how many items in the list can be selected at a time. #
/istBo+ control can provide single or multiple selections using the -electionMode property .
)f you want to retrieve a single selected item to a variable , you can code li"e this
Dim "ar As Strin
"ar 5 )istBox..SelectedItem
)f you change the selection mode property to multiple select , then you will retrieve a collection
of items from /istBo+A.-elected)tems property.
)istBox..Selection7ode 5 Selection7ode.7ultiSimple
The following VB.Net program initially fill seven days in a wee" while in the form load event
and set the selection mode property to Multi-imple. #t the Button clic" event it will display the
selected items.
Source code
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
MyBase./oad
/istBo+A.)tems.#dd0G-undayG1
/istBo+A.)tems.#dd0GMondayG1
/istBo+A.)tems.#dd0GTuesdayG1
/istBo+A.)tems.#dd0GWednesdayG1
/istBo+A.)tems.#dd0GThursdayG1
/istBo+A.)tems.#dd0G!ridayG1
/istBo+A.)tems.#dd0G-aturdayG1
/istBo+A.-electionMode F -electionMode.Multi-imple
End -ub
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im ob9 #s b9ect
!or Each ob9 )n /istBo+A.-elected)tems
MsgBo+0ob9.To-tring1
Ne+t
End -ub
End %lass
!4E!M )IST B#F
The %hec"ed/istBo+ control gives you all the capability of a list bo+ and also allows you to
display a chec" mar" ne+t to the items in the list bo+.
To add ob9ects to the list at run time, assign an array of ob9ect references with the #dd2ange
method. The list then displays the default string value for each ob9ect.
Dim days As Strin13 5 N6Sunday6- 67onday6- 6Tuesday6O
c%ec0ed)istBox..Items.Add(ane1days3
?ou can add individual items to the list with the #dd method. The %hec"ed/istBo+ ob9ect
supports three states through the %hec"-tate enumeration= %hec"ed, )ndeterminate, and
3nchec"ed.
!%ec0ed)istBox..Items.Add16Sunday6- !%ec0State.!%ec0ed3
!%ec0ed)istBox..Items.Add167onday6- !%ec0State.=nc%ec0ed3
!%ec0ed)istBox..Items.Add16Tuesday6- !%ec0State.Indeterminate3
Source !ode
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
MyBase./oad
%hec"ed/istBo+A.)tems.#dd0G-undayG, %hec"-tate.%hec"ed1
%hec"ed/istBo+A.)tems.#dd0GMondayG, %hec"-tate.3nchec"ed1
%hec"ed/istBo+A.)tems.#dd0GTuesdayG, %hec"-tate.)ndeterminate1
%hec"ed/istBo+A.)tems.#dd0GWednesdayG, %hec"-tate.%hec"ed1
%hec"ed/istBo+A.)tems.#dd0GThursdayG, %hec"-tate.3nchec"ed1
%hec"ed/istBo+A.)tems.#dd0G!ridayG, %hec"-tate.)ndeterminate1
%hec"ed/istBo+A.)tems.#dd0G-aturdayG, %hec"-tate.)ndeterminate1
End -ub
End %lass
(ADI# B=TT#N
# radio button or option button is a type of graphical user interface element that allows the user
to choose only one of a predefined set of options. When a user clic"s on a radio button, it
becomes chec"ed, and all other radio buttons with same group become unchec"ed
The radio button and the chec" bo+ are used for different functions. 3se a radio button when you
want the user to choose only one option. When you want the user to choose all appropriate
options, use a chec" bo+. /i"e chec" bo+es, radio buttons support a %hec"ed property that
indicates whether the radio button is selected.
Source code
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles MyBase./oad
2adioButtonA.%hec"ed F True
End -ub
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
)f 2adioButtonA.%hec"ed F True Then
MsgBo+0G?ou are selected 2ed OO G1
E+it -ub
Else)f 2adioButton5.%hec"ed F True Then
MsgBo+0G?ou are selected Blue OO G1
E+it -ub
Else
MsgBo+0G?ou are selected 7reen OO G1
E+it -ub
End )f
End -ub
End %lass
!4E!M B#F
%hec" Bo+es allow the user to ma"e multiple selections from a number of options. ?ou can clic"
a chec" bo+ to select it and clic" it again to deselect it.
%hec"Bo+es comes with a caption, which you can set in the Te+t property.
!%ec0Box..Text 5 6Net,in'ormations.com6
?ou can use the %hec"Bo+ control Three-tate property to direct the control to return the
%hec"ed, 3nchec"ed, and )ndeterminate values. ?ou need to set the chec" bo+s Three-tate
property to True to indicate that you want it to support three states.
!%ec0Box..T%reeState 5 True
To apply the same property settings to multiple %hec"Bo+ controls, use the -tyle property. The
following VB.Net program shows how to find a chec"bo+ is selected or not.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im msg #s -tring F GG
)f %hec"Bo+A.%hec"ed F True Then
msg F Gnet.informations.comG
End )f
)f %hec"Bo+5.%hec"ed F True Then
msg F msg H G vb.net.informations.comG
End )f
)f %hec"Bo+4.%hec"ed F True Then
msg F msg H G csharp.net.informations.comG
End )f
)f msg./ength L D Then
MsgBo+0msg H G selected G1
Else
MsgBo+0GNo chec"bo+ selectedG1
End )f
%hec"Bo+A.Three-tate F True
End -ub
End %lass
PI!T=(E B#F
The Windows !orms $ictureBo+ control is used to display images in bitmap, 7)!,icon, or '$E7
formats.
?ou can set the )mage property to the )mage you want to display, either at design time or at run
time. ?ou can programmatically change the image displayed in a picture bo+, which is
particularly useful when you use a single form to display different pieces of information.
PictureBox..Imae 5 Imae.&rom&ile16!:KtestImae.2p63
The -i:eMode property, which is set to values in the $ictureBo+-i:eMode enumeration, controls
the clipping and positioning of the image in the display area.
PictureBox..SiPe7ode 5 PictureBoxSiPe7ode.Stretc%Imae
There are five different $ictureBo+-i:eMode is available to $ictureBo+ control.
AutoSiPe , SiPes t%e picture box to t%e imae.
!enterImae , !enters t%e imae in t%e picture box.
Normal , Places t%e upper,le't corner o' t%e imae at upper
le't in t%e picture box
Stretc%Imae , Allo$s you to stretc% t%e imae in code
?ou can change the si:e of the display area at run time with the %lient-i:e property.
pictureBox..!lientSiPe 5 Ne$ SiPe1xSiPe- ySiPe3
The following VB.Net program shows how to load a picture from a file and display it in streach
mode.
P(#<(ESS BA(
The $rogressBar control visually indicates the progress of a lengthy operation such as calculating
a comple+ result, downloading a large file from the Web etc.
The Ma+imum and Minimum properties define the range of values to represent the progress of a
tas".
7inimum : Sets t%e lo$er "alue 'or t%e rane o' "alid "alues 'or proress.
7aximum : Sets t%e upper "alue 'or t%e rane o' "alid "alues 'or proress.
Value : T%is property obtains or sets t%e current le"el o' proress.
By default, Minimum and Ma+imum are set to D and ADD. #s the tas" proceeds, the $rogressBar
fills in from the left to the right. To delay the program briefly so that you can view changes in the
progress bar clearly.
The following VB.Net program shows a simple operation in a progress bar .
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im i #s )nteger
$rogressBarA.Minimum F D
$rogressBarA.Ma+imum F 5DD
!or i F D To 5DD
$rogressBarA.Value F i
Ne+t
End -ub
End %lass
S!(#)) BA(
The hori:ontal and vertical scrollbars which the user can use to move content into view.
Most of the controls that use scrollbars come with them built in, such as multiline te+t bo+es,
combo bo+es etc. ?ou can set the Value property yourself in code, which moves the scroll bo+ to
match. The controls Value property gets and sets its current numeric value.
The Minimum and Ma+imum properties determine the range of values that the control can
display. The following VB.Net program shows a Te+tBo+ control with scrollbars.
-ource code
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
MyBase./oad
Te+tBo+A.Multiline F True
Te+tBo+A.-crollBars F -crollBars.Both
End -ub
End %lass
DATE AND TI7E PI!ME(
The ,ateTime$ic"er control allows you to display and collect date and time from the user with a
specified format.
The ,ateTime$ic"er control prompts the user for a date or time using a graphical calendar with
scroll arrows. The most important property of the ,ateTime$ic"er is the Value property, which
holds the selected date and time.
DateTimePic0er..Value 5 6.8?9.?8>.>6
The Value property is set to the current date by default. ?ou can use the Te+t property or the
appropriate
member of Value to get the date and time value.
Dim idate As Strin
idate 5 DateTimePic0er..Value
The control can display one of several styles, depending on its property values. The values can
be displayed in four
formats, which are set by the !ormat property= /ong, -hort, Time, or %ustom.
DateTimePic0er..&ormat 5 DateTimePic0er&ormat.S%ort
The following VB.Net program shows how to set and get the value of a ,ateTime$ic"erA
control.
Source code
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
MyBase./oad
,ateTime$ic"erA.!ormat F ,ateTime$ic"er!ormat.-hort
,ateTime$ic"erA.Value F GA5@4A@5DADG
End -ub
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im idate #s -tring
idate F ,ateTime$ic"erA.Value
MsgBo+0G-elected date is = G H idate1
End -ub
End %lass
T(EE VIEH
Tree View control is used to display hierarchical tree li"e information such as a directory
hierarchy. The top level in a tree view are root nodes that can be e+panded or collapsed if the
nodes have child nodes.
The user can e+pand the TreeNode by clic"ing the plus sign 0(1 button, if one is displayed ne+t
to the TreeNode, or you can e+pand the TreeNode by calling the TreeNode.E+pand method.
When a parent node is e+panded, its child nodes are visible. ?ou can also navigate through tree
views with various properties= !irstNode, /astNode, Ne+tNode, $revNode, Ne+tVisibleNode,
$revVisibleNode.
The fullpath method of treeview control provides the path from root node to the selected node.
TreeViewA.-electedNode.!ull$ath
Tree nodes can optionally display chec" bo+es. To display the chec" bo+es, set the %hec"Bo+es
property of the TreeView to true.
TreeViewA.%hec"Bo+es F True
The following Vb.Net program shows a simple demonstration of treeview control
Source code
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
MyBase./oad
,im tNode #s TreeNode
tNode F TreeViewA.Nodes.#dd0GWebsitesG1
TreeViewA.Nodes0D1.Nodes.#dd0GNet.informations.comG1
TreeViewA.Nodes0D1.Nodes0D1.Nodes.#dd0G%/2G1
TreeViewA.Nodes0D1.Nodes.#dd0GVb.net.informations.comG1
TreeViewA.Nodes0D1.Nodes0A1.Nodes.#dd0G-tring TutorialG1
TreeViewA.Nodes0D1.Nodes0A1.Nodes.#dd0GE+cel TutorialG1
TreeViewA.Nodes0D1.Nodes.#dd0G%sharp.net.informations.comG1
TreeViewA.Nodes0D1.Nodes051.Nodes.#dd0G#,.NETG1
TreeViewA.Nodes0D1.Nodes051.Nodes0D1.Nodes.#dd0G,atasetG1
End -ub
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
MsgBo+0TreeViewA.-electedNode.!ull$ath1
End -ub
End %lass
)IST VIEH
/ist views displays a collection of items that can be displayed using one of five different views,
such as /arge)con, ,etails , -mall)con, /ist and Tile.
/istView provides a large number of properties that provide fle+ibility in appearance and
behavior. The View property allows you to change the way in which items are displayed. and the
-electionMode property determines how many items in the list can be selected at a time.
The following Vb.Net program first set its view property as ,etails and 7rid/ines property as
true and !ull2ow-elect as true.
)istVie$..Vie$ 5 Vie$.Details
)istVie$..<rid)ines 5 True
)istVie$..&ull(o$Select 5 True
#fter that it fills column header and then the column values.
)istVie$..!olumns.Add16ProductName6- .>>3
!inally in the button clic" event, it will display the selected row values in a message bo+.
Source code
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
MyBase./oad
66-et view property
/istViewA.View F View.,etails
/istViewA.7rid/ines F True
/istViewA.!ull2ow-elect F True
6#dd column header
/istViewA.%olumns.#dd0G$roductNameG, ADD1
/istViewA.%olumns.#dd0G$riceG, BD1
/istViewA.%olumns.#dd0GPuantityG, BD1
6#dd items in the listview
,im arr041 #s -tring
,im itm #s /istView)tem
6#dd first item
arr0D1 F GproductEAG
arr0A1 F GADDG
arr051 F GADG
itm F New /istView)tem0arr1
/istViewA.)tems.#dd0itm1
6#dd second item
arr0D1 F GproductE5G
arr0A1 F G5DDG
arr051 F G5DG
itm F New /istView)tem0arr1
/istViewA.)tems.#dd0itm1
End -ub
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im productName #s -tring
,im price #s -tring
,im *uantity #s -tring
productName F /istViewA.-elected)tems.)tem0D1.-ub)tems0D1.Te+t
price F /istViewA.-elected)tems.)tem0D1.-ub)tems0A1.Te+t
*uantity F /istViewA.-elected)tems.)tem0D1.-ub)tems051.Te+t
MsgBo+0productName H G , G H price H G , G H *uantity1
End -ub
End %lass
7EN= !#NT(#)
# menu is located on the menu bar and contains a list of related commands. MainMenu is the
container for the Menu structure of the form and menus are made of Menu)tem ob9ects that
represent individual parts of a menu.
?ou can create a main menu ob9ect on your form using the MainMenu control. The following
picture shows how to drag the Menustrip b9ect to the !orm.
#fter drag the Menustrip on your form you can directly create the menu items by type a value
into the GType 8ereG bo+ on the menubar part of your form. !rom the following picture you can
understand how to create each menu items on mainmenu b9ect.
)f you need a separator bar , right clic" on your menu then go to insert.L-eparator.
#fter creating the Menu on the form , you have to double clic" on each menu item and write the
programs there depends on your re*uirements. The following Vb.Net program shows how to
show a messagebo+ when clic"ing a menu item.
Source code
$ublic %lass !ormA
$rivate -ub Menu)temATool-tripMenu)temE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s
-ystem.Event#rgs1 8andles Menu)temATool-tripMenu)tem.%lic"
MsgBo+0G?ou are selected Menu)temEAG1
End -ub
End %lass
7DI &#(7
# Multiple ,ocument )nterface 0M,)1 programs can display multiple child windows inside
them.
This is in contrast to single document interface 0-,)1 applications, which can manipulate only
one document at a time. Visual -tudio Environment is an e+ample of Multiple ,ocument
)nterface 0M,)1 and notepad is an e+ample of an -,) application, opening a document closes
any previously opened document. #ny windows can become an M,) parent, if you set the
)sMdi%ontainer property to True.
Is7di!ontainer 5 True
The following vb.net program shows a M,) form with two child forms. %reate a new VB.Net
pro9ect, then you will get a default form !ormA . Then add two mnore forms in the pro9ect
0!orm5 , !orm 41 . %reate a Menu on your form and call these two forms on menu clic" event.
%lic" the following lin" to see how to create a Menu on your form 8ow to Menu %ontrol
VB.Net.
Source code
$ublic %lass !ormA
$rivate -ub !ormAE/oad0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles MyBase./oad
)sMdi%ontainer F True
End -ub
$rivate -ub Menu)temATool-tripMenu)temE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s
-ystem.Event#rgs1 8andles Menu)temATool-tripMenu)tem.%lic"
,im frm5 #s New !orm5
frm5.-how01
frm5.Mdi$arent F Me
End -ub
$rivate -ub Menu)tem5Tool-tripMenu)temE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s
-ystem.Event#rgs1 8andles Menu)tem5Tool-tripMenu)tem.%lic"
,im frm4 #s New !orm4
frm4.-how01
frm4.Mdi$arent F Me
End -ub
End %lass
!#)#( DIA)#< B#F
There are several classes that implement common dialog bo+es, such as color selection and print
setup etc.
The user can choose a color from either a set of basic or custom color palettes. ?ou can invite a
color dialog bo+ by calling -how,ialog01 method.
Dim dl As Ne$ !olorDialo
dl.S%o$Dialo13
The %olor dialog bo+ has a full version and a partial version of the user interface. The full
version includes the basic controls and has additional controls that allow the user to create
custom colors. The partial version has controls that display the basic and custom color palettes
from which the user can select a color value. The system stores internal colors as 45.bit 27B
values that have the following he+adecimal form= D+DDbbggrr.
The following Vb.Net program invites a color dialog bo+ and retrieve the selected color to a
string.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im dlg #s New %olor,ialog
dlg.-how,ialog01
)f dlg.-how,ialog F Windows.!orms.,ialog2esult.M Then
,im str #s -tring
str F dlg.%olor.Name
MsgBo+0str1
End )f
End -ub
End %lass
&#NT DIA)#< B#F
,ialog bo+es consist of a title bar , an optional main instruction , various controls in the content
area , and commit buttons . The !ont dialog bo+ lets the user choose attributes for a logical font,
such as font family and associated font style, point si:e, effects, and a script.
The following VB.Net program invites a !ont ,ialog Bo+ and retrieve the selected !ont Name
and !ont -i:e.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im dlg #s New !ont,ialog
dlg.-how,ialog01
)f dlg.-how,ialog F Windows.!orms.,ialog2esult.M Then
,im fontName #s -tring
,im font-i:e #s )nteger
fontName F dlg.!ont.Name
font-i:e F dlg.!ont.-i:e
MsgBo+0fontName H G G H font-i:e1
End )f
End -ub
End %lass
#PEN DIA)#< B#F
The pen!ile,ialog component displays a dialog bo+ that allows the user to choose a file to
open.
The !ileName property can be set prior to showing the dialog bo+. This causes the dialog bo+ to
initially display the given filename. )n most cases, your applications should set the
)nitial,irectory, !ilter, and !ilter)nde+ properties prior to calling -how,ialog.
The following VB.Net program invites an pen!ile ,ialog Bo+ and retrieve the selected
filename to a string.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im dlg #s New pen!ile,ialog
dlg.-how,ialog01
)f dlg.-how,ialog F Windows.!orms.,ialog2esult.M Then
,im fileName #s -tring
fileName F dlg.!ileName
MsgBo+0fileName1
End )f
End -ub
End %lass
P(INT DIA)#< B#F
The $rint,ialog component displays a dialog bo+ that allows the user to choose printer settings
for a document. The user can specify the printer to use, the range of pages to print, and the
number of copies.
The $rint dialog bo+ includes a $rint 2ange group of radio buttons that indicate whether the user
wants to print all pages, a range of pages, or only the selected te+t. The dialog bo+ includes an
edit control in which the user can type the number of copies to print. The $rint To !ile chec" bo+
indicates whether the user wants to send output to a file rather than to a printer. By default, the
$rint dialog bo+ initially displays information about the current default printer.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, ByVal e #s -ystem.Event#rgs1 8andles
ButtonA.%lic"
,im dlg #s New $rint,ialog
dlg.-how,ialog01
End -ub
End %lass
A((AY )IST
Array)ist is one of the most fli+ible data structure from VB.NET %ollections. #rray/ist
contains a simple list of values and very easily we can add , insert , delete , view etc.. to do with
#rray/ist. )t is very fle+ible becuse we can add without any si:e information , that is it grow
dynamically and also shrin" .
Important 'unctions in Array)ist
Add : Add an Item in an Array)ist
Insert : Insert an Item in a speci'ied position in an Array)ist
(emo"e : (emo"e an Item 'rom Array)ist
(emo"eAt: remeo"e an item 'rom a speci'ied position
Sort : Sort Items in an Array)ist
4o$ to add an Item in an Array)ist Q
ynta- : Array;ist.add.Item/
Item : The Item to be add the Array;ist
,im )tem/ist #s New #rray/ist01
)tem/ist.#dd0G)tem<G1
4o$ to Insert an Item in an Array)ist Q
ynta- : Array;ist.insert.inde-3item/
inde- : The position o$ the item in an Array;ist
Item : The Item to be add the Array;ist
)tem/ist.)nsert04, Gitem;G1
4o$ to remo"e an item 'rom array)ist Q
ynta- : Array;ist.Remove.item/
Item : The Item to be add the Array;ist
)tem/ist.2emove0Gitem5G1
4o$ to remo"e an item in a speci'ied position 'rom an Array)ist Q
ynta- : Array;ist.RemoveAt.inde-/
inde- : the position o$ an item to remove $rom an Array;ist
)tem/ist.2emove#t051
4o$ to sort Array)ist Q
ynta- : Array;istort./
The following VB.NET source code shows some function in #rray/ist
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im i #s )nteger
,im )tem/ist #s New #rray/ist01
)tem/ist.#dd0G)tem<G1
)tem/ist.#dd0G)temIG1
)tem/ist.#dd0G)tem5G1
)tem/ist.#dd0G)temAG1
)tem/ist.#dd0G)tem4G1
MsgBo+0G-hows #dded )temsG1
!or i F D To )tem/ist.%ount . A
MsgBo+0)tem/ist.)tem0i11
Ne+t
6insert an item
)tem/ist.)nsert04, G)tem;G1
6sort itemms in an arraylist
)tem/ist.-ort01
6remove an item
)tem/ist.2emove0G)temAG1
6remove item from a specified inde+
)tem/ist.2emove#t041
MsgBo+0G-hows final )tems the #rray/istG1
!or i F D To )tem/ist.%ount . A
MsgBo+0)tem/ist.)tem0i11
Ne+t
End -ub
End %lass
4as% table
8ashTable stores a Mey Value pair type collection of data . We can retrive items from hashTable
to provide the "ey . Both "ey and value are b9ects.
T%e common 'unctions usin in 4as%table are :
Add : To add a pair o' "alue in 4as%Table
ynta- : =ashTable.Add.>ey3Value/
>ey : The >ey value
Value : The value o$ corrosponding !ey
!ontainsMey : !%ec0 i' a speci'ied 0ey exist or not
ynat- : =ashTable.6ontains>ey.!ey/
>ey : The >ey value $or search in =ahTable
!ontainsValue : !%ec0 t%e speci'ied Value exist in 4as%Table
ynat- : =ashTable.6ontainsValue.Value/
Value : earch the speci$ied Value in =ashTable
(emo"e : (emo"e t%e speci'ied Mey and corrospondin Value
ynta- : =ashTable.Remove.>ey/
>ey : The argument !ey o$ deleting pairs
The following source code shows all important operations in a 8ashTable
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im wee"s #s New 8ashtable
,im day #s ,ictionaryEntry
wee"s.#dd0GAG, G-unG1
wee"s.#dd0G5G, GMonG1
wee"s.#dd0G4G, GTueG1
wee"s.#dd0G<G, GWedG1
wee"s.#dd0GIG, GThuG1
wee"s.#dd0G;G, G!riG1
wee"s.#dd0GBG, G-atG1
6,isplay a single )tem
MsgBo+0wee"s.)tem0GIG11
6-earch an )tem
)f wee"s.%ontainsValue0GTueG1 Then
MsgBo+0G!indG1
Else
MsgBo+0GNot findG1
End )f
6remove an )tem
wee"s.2emove0G4G1
6,isplay all "ey value pairs
!or Each day )n wee"s
MsgBo+0day.Mey G .. G day.Value1
Ne+t
End -ub
End %lass
Stac0
-tac" is one of another easy to use VB.NET %ollections . -tac" follows the push.pop operations,
that is we can $ush )tems into -tac" and $op it later also it follows the /ast )n !irst ut 0/)!1
system. That is we can push the items into a stac" and get it in reverse order. -tac" returns the
last item first.
!ommonly used met%ods :
Pus% : Add 1Pus%3 an item in t%e stac0 datastructure
ynta- : tac!.2ush.5b?ect/
5b?ect : The item to be inserted.
Pop : Pop return t%e item last Item to insert in stac0
ynta- : tac!.2op./
Return : The last ob?ect in the tac!
!ontains : !%ec0 t%e ob2ect contains in t%e stac0
ynta- : tac!.6ontains.5b?ect/
5b?ect : The speci$ied 5b?ect to be seach
The following VB.NET -ource code shows some of commonly used functions =
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im stac"Table #s New -tac"
stac"Table.$ush0G-unG1
stac"Table.$ush0GMonG1
stac"Table.$ush0GTueG1
stac"Table.$ush0GWedG1
stac"Table.$ush0GThuG1
stac"Table.$ush0G!riG1
stac"Table.$ush0G-atG1
)f stac"Table.%ontains0GWedG1 Then
MsgBo+0stac"Table.$op011
Else
MsgBo+0Gnot e+istG1
End )f
End -ub
End %lass
Rueue
The Pueue is another adtastructure from VB.NET %ollections . Pueue wor"s li"e !irst )n !irst
ut method and the item added first in the Pueue is first get out from Pueue. We can En*ueue
0add1 items in Pueue and we can ,e*ueue 0remove from Pueue 1 or we can $ee" 0that is get the
reference of first item added in Pueue 1 the item from Pueue.
T%e commonly usin 'unctions are 'ollo$s :
EnSueue : Add an Item in Rueue
ynta- : tac!.En@ueue.5b?ect/
5b?ect : The item to add in Aueue
DeSueue : (emo"e t%e oldest item 'rom Rueue 1$e dont et t%e item later3
ynta- : tac!.De@ueue./
Returns : Remove the oldest item and return.
Pee0 : <et t%e re'erence o' t%e oldest item 1it is not remo"ed permenantly3
ynta- : tac!.2ee!./
returns : <et the re$erence o$ the oldest item in the Aueue
The following VB.NET -ource code shows some of commonly used functions =
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im *ueue/ist #s New Pueue
*ueue/ist.En*ueue0G-unG1
*ueue/ist.En*ueue0GMonG1
*ueue/ist.En*ueue0GTueG1
*ueue/ist.En*ueue0GWedG1
*ueue/ist.En*ueue0GThuG1
*ueue/ist.En*ueue0GfriG1
*ueue/ist.En*ueue0G-atG1
MsgBo+0*ueue/ist.,e*ueue011
MsgBo+0*ueue/ist.$ee"011
)f *ueue/ist.%ontains0G-unG1 Then
MsgBo+0G%ontains -un G1
Else
MsgBo+0GNot %ontains -un G1
End )f
End -ub
End %lass
Array
Arrays are using for store similar data types grouping as a single unit. We can access Array
elements by its numeric inde+.
Dim 9ee!.1/ As tring
The above Vb.Net statements means that , an #rray named as wee" declared as a -tring type and
it can have the capability of seven -tring type values.
9ee!.(/ # )unday)
9ee!.'/ # ),onday)
)n the above statement , we initiali:e the values to the -tring #rray. 9ee!.(/ # )unday) means ,
we initiali:e the first value of #rray as G-undayG ,
Dim 9ee!Name as tring # 9ee!.'/
We can access the #rrays elements by providing its numerical inde+, the above statement we
access the second value from the wee" #rray.
)n the following program , we declare an #rray Gwee"G capability of seven -tring values and
assigns the seven values as days in a wee" . Ne+t step is to retrieve the elements of the #rray
using a !or loop. !or finding the end of an #rray we used the /ength function of #rray b9ect.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im i #s )nteger
,im wee"0;1 #s -tring
wee"0D1 F G-undayG
wee"0A1 F GMondayG
wee"051 F GTuesdayG
wee"041 F GWednesdayG
wee"0<1 F GThursdayG
wee"0I1 F G!ridayG
wee"0;1 F G-aturdayG
!or i F D To wee"./ength . A
MsgBo+0wee"0i11
Ne+t
End -ub
End %lass
Dynamic array
Dynamic Arrays can resi:e the capability of the #rray at runtime .when you are in a situation
that you do not "now e+actly the number of elements to store in array while you ma"ing the
program. )n that situations we are using Dynamic Array .
Initial declaration
Dim scores./ As Integer
(esiPin
ReDim scores.'/
)f you want to "eep the e+isting items in the #rray , you can use the "eyword $reserve .
ReDim 2reserve scores.&/
)n this case the #rray dynamically allocate one more -tring value and "eep the e+isting values.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im i #s )nteger
,im scores01 #s )nteger
2e,im scores0A1
scores0D1 F ADD
scores0A1 F 5DD
!or i F D To scores./ength . A
MsgBo+0scores0i11
Ne+t
2e,im $reserve scores051
scores051 F 4DD
!or i F D To scores./ength . A
MsgBo+0scores0i11
Ne+t
End -ub
End %lass
Name and "alue collection
NameValue!ollection is used to store data li"e Name, Value format. )t is very similar to Vb.Net
8ashTable, 8ashTable also stores data in Mey , value format . NameValue!ollection can hold
more than one value for a corresponding Mey.
#dding new pairs
Add.ByVal name As tring3 ByVal value As tring/
#dd0G8ighG,GCDG1
7et the value of corresponding Mey
<etValues.ByVal name As tring/ As tring./
-tring values01 F 7etValues0G8ighG1
Source code
)mports -ystem.%ollections.-peciali:ed
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im mar"-tatus #s New NameValue%ollection
,im "ey #s -tring
,im values01 #s -tring
mar"-tatus.#dd0GVery 8ighG, GCDG1
mar"-tatus.#dd0G8ighG, G;DG1
mar"-tatus.#dd0GmediumG, GIDG1
mar"-tatus.#dd0G$assG, G<DG1
!or Each "ey )n mar"-tatus.Meys
values F mar"-tatus.7etValues0"ey1
!or Each value #s -tring )n values
MsgBo+0"ey H G . G H value1
Ne+t value
Ne+t "ey
End -ub
End %lass
Strin lent%
The )ent%13 function in Strin !lass returned the number of characters occurred in a -tring.
ystem.tring.;ength./ As Integer
(eturns:
)nteger = The number of characters in the specified -tring
!or e+=
GThis is a TestG./ength01 returns A<.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring
str F GThis is a TestG
MsgBo+0str./ength011
End -ub
End %lass
Strin insert
The Insert13 function in Strin !lass will insert a -tring in a specified inde+ in the -tring
instance.
ystem.tring.Insert.Integer ind3 tring str/ as tring
Parameters:
ind . The inde+ of the specified string to be inserted.
str . The string to be inserted.
(eturns:
-tring . The result string.
Exceptions:
ystem.Argument5ut5$RangeE-ception: start)nde+ is negative or greater than the length of this
instance
ystem.ArgumentNullE-ception : )f the argument is null.
!or e+=
GThis is TestG.)nsert0C,G)nsert G1 returns GThis is )nsert TestG
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring F GThis is VB.NET TestG
,im ins-tr #s -tring F G)nsert G
,im str2es #s -tring F str.)nsert0AI, ins-tr1
MsgBo+0str2es1
End -ub
End %lass
Strin index o'
The Index#' method in Strin !lass returns the inde+ of the first occurrence of the specified
substring.
ystem.tring.Inde-5$.tring str/ As Integer
Parameters:
str . The parameter string to chec" its occurrences
(eturns:
)nteger . )f the parameter -tring occurred as a substring in the specified -tring
it returns position of the first character of the substring .
)f it does not occur as a substring, .A is returned.
Exceptions:
ystem.ArgumentNullE-ception: )f the #rgument is null.
!or e+=
GThis is a testG.)nde+f0GTestG1 returns AD
GThis is a testG.)nde+f0GvbG1 returns .A
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring
str F GVB.NET T$ AD BM-G
MsgBo+0str.)nde+f0GBM-G11
End -ub
End %lass
Strin 'ormat
VB.NET Strin &ormat method replace the argument b9ect into a te+t e*uivalent
-ystem.-triing.
ystem.4ormat.ByVal $ormat As tring3 ByVal arg( As 5b?ect/ As tring
Parameters:
-tring format = The format -tring
The format -tring -ynta+ is li"e Qinde+Number=format%haracterR
b9ect argD = The ob9ect to be formatted.
(eturns:
-tring = The formatted -tring
Exceptions:
ystem.ArgumentNullE-ception : The format -tring is null.
ystem.4ormatE-ception : The format item in format is invalid.
The number indicating an argument to format is less than :ero, or greater than or e*ual to the
number of specified ob9ects to format.
!or e+ =
!urrency :
tring.4ormat.)B(:cC)3 '(/ will return SAD.DD
The currency symbol 0S1 displayed depends on the global locale settings.
Date :
tring.4ormat.)Today:s date is B(:DC)3 DateTime.No9/
?ou will get Today6s date li"e = DA 'anuary 5DDI
Time :
tring.4ormat.)The current time is B(:TC)3 DateTime.No9/
?ou will get %urrent Time /i"e = AD=AD=A5
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im dNum #s ,ouble
dNum F 45.A54<I;BCJ
MsgBo+0G!ormated -tring G H -tring.!ormat0GQD=n<RG, dNum11
End -ub
End %lass
Strin eSuals
VB.NET Strin ESuals function is to chec" the specified two -tring b9ect values are same or
not
ystem.tring.E@uals.tring str'3 tring str&/ As Boolean
Parameters:
-tring strA = The -tring argument
-tring str5 = The -tring argument
(eturns:
Boolean = ?es@No
)t return the values of the two -tring b9ects are same
!or e+ =
-trA F GE*uals01G
-tr5 F GE*uals01G
tring.E@uals.tr'3tr&/ returns True
tring.E@uals.tr'.To;o9er3tr&/ returns !alse
Because the -tring b9ects values are different
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im strA #s -tring F GE*ualsG
,im str5 #s -tring F GE*ualsG
)f -tring.E*uals0strA, str51 Then
MsgBo+0G-trings are E*ual01 G1
Else
MsgBo+0G-trings are not E*ual01 G1
End )f
End -ub
End %lass
Strin copy to
VB.NET Strin !opyTo method %opies a specified number of characters from a specified
position in this instance to a specified position in an array of characters.
ystem.tring.6opyTo.ByVal sourceInde- As Integer3 ByVal destination./ As 6har3 ByVal
destinationInde- As Integer3 ByVal count As Integer/
Parameters:
)nteger source)nde+ = The starting position of the source -tring
%har destination01 = The character #rray
)nteger destination)nde+ = #rray element in the destination
)nteger count = The number of characters to destination
Exceptions:
ystem.ArgumentNullE-ception : )f the destination is null
ystem.Argument5ut5$RangeE-ception :
-ource )nde+, ,estination)ndes or %ount is a .ve value
%ount is greater than the length of the substring from start)nde+ to the end of this instance
count is greater than the length of the subarray from destination)nde+ to the end of destination
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im strA #s -tring F G%opyTo01 sampleG
,im chrs0I1 #s %har
strA.%opyTo0D, chrs, D, ;1
MsgBo+0chrs0D1 ( chrs0A1 ( chrs051 ( chrs041 ( chrs0<1 ( chrs0I11
End -ub
End %lass
Strin copy
VB.NET Strin !opy method is create a new -tring ob9ect with the same content
ystem.tring.6opy.ByVal str As tring/ As tring
Parameters:
-tring str = The argument -tring for %opy method
(eturns:
-tring = 2eturns a new -tring as the same content of argument -tring
E+ceptions=
ystem.ArgumentNullE-ception : )f the argument is null.
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im strA #s -tring
,im str5 #s -tring
strA F GVB.NET %opy01 testG
str5 F -tring.%opy0strA1
MsgBo+0str51
End -ub
End %lass
Strin contains
The !ontains method in the VB.NET Strin !lass chec" the specified parameter -tring e+ist in
the -tring
ystem.tring.6ontains.tring str/ As Boolean
Parameters:
-tring str . input -tring for search
(eturns:
Boolean . ?es@No
)f the str %ontains in the -tring then it returns true
)f the str does not %ontains in the -tring it returns !alse
!or e+= GThis is a TestG.%ontains0GisG1 return True
GThis is a TestG.%ontains0GyesG1 return !alse
E+ceptions=
ystem.ArgumentNullE-ception : )f the argument is null
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring
str F GVB.NET T$ AD BM-G
)f str.%ontains0GT$G1 F True Then
MsgBo+0GThe string %ontains01 6T$6 G1
Else
MsgBo+0GThe -tring does not %ontains01 6T$6G1
End )f
End -ub
End %lass
Strin compare
The VB.NET Strin !ompare function is use to compare two -tring b9ects.
ystem.tring.6ompare.tring str'3tring str&3 Boolean / As Integer
)t returns an )nteger indication le+ical relationship between the two comprehends
Parameters:
-tring strA = $arameter -tring
-tring str5 = $arameter -tring
Boolean True@!alse )ndication to chec" the -tring with case sensitive or without case sensitive
(eturns:
)nteger = returns less than :ero, :ero or greater than :ero.
/ess than :ero = strA is less than str5
:ero = strA is e*ual to str5
7reater than :ero = strA is grater than str5
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im strA #s -tring
,im str5 #s -tring
strA F Gvb.netG
str5 F GVB.NETG
,im result #s )nteger
result F -tring.%ompare0strA, str51
MsgBo+0result1
result F -tring.%ompare0strA, str5, True1
MsgBo+0result1
End -ub
End %lass
Strin clone
The VB.NET Strin !lone13 method returns a reference to this instance of -tring.
2ublic 4unction 6lone./ As 5b?ect
(eturns:
b9ect = 2eturn the instance of the -tring
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring F G%lone01 TestG
,im cloned-tring #s -tring
cloned-tring F str.%lone01
MsgBo+0cloned-tring1
End -ub
End %lass
When you run this program you ill get the same content of the first string G%lone01 TestG
Strin c%ars
The VB.NET Strin !%ars method return the character at the specified inde+ of an instance
ystem.tring.6hars.ByVal inde- As Integer/ As 6har
Parameters:
)nteger inde+ . The character position in the returned %haracter.
(eturns:
%har . The return %haracter.
!or e+ =
G2eturn testG.%hars041 return a single character 6u6
)f u pass a number more than -tring length will return an e+ception
G2eturn testG.%hars05I1 will throw a -ystem.)nde+utf2angeE+ception
E+ceptions=
ystem.Inde-5ut5$RangeE-ception : The inde+ is less than :ero or greater than the length of
-tring b9ect
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring F G2eturned %haracter %hars01G
,im single%har #s %har
single%har F str.%hars041
MsgBo+0single%har1
End -ub
End %lass
When you run this source code you will return a messagebo+ show 6u6
Sub strin
Substrin in Vb.Net Strin !lass returns a new string that is a substring of this string. The
substring begins at the specified given inde+ and e+tended up to the given length.
2ublic 4unction ubstring.ByVal startInde- As Integer3 ByVal length As Integer/ As tring
Parameters:
start)nde+= The inde+ of the start of the substring.
length= The number of characters in the substring.
(eturns:
The specified substring.
Exceptions:
ystem.Argument5ut5$RangeE-ception = the begin)nde+ or length less than :ero, or the begin
inde+ ( length not within the specified string
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring
,im ret-tring #s -tring
str F GThis is substring testG
ret-tring F str.-ubstring0C, J1
MsgBo+0ret-tring1
End -ub
End %lass
When you e+ecute this program , its will display GsubtringG in the messagebo+.
-tring split
Vb.Net Strin Split function returns an array of -tring containing the substrings delimited by
the given -ystem.%har array.
2ublic 4unction plit.ByVal 2aramArray separator./ As 6har/ As tring./
Parameters:
separator . the given delimiter
(eturns:
#n array of -trings delimited by one or more characters in separator
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring
,im str#rr01 #s -tring
,im count #s )nteger
str F Gvb.net split testG
str#rr F str.-plit0G G1
!or count F D To str#rr./ength . A
MsgBo+0str#rr0count11
Ne+t
End -ub
End %lass
When you e+ecute this programme , you will get Gvb.netG GsplitG GtestG in separate messagebo+
End $it%
EndsHit% in VB.NET -tring %lass chec" if the $arameter -tring EndsHit% the -pecified -tring
ystem.tring.EndsDith.tring su$$i-/ as Boolean
Parameters:
suffi+ . The passing -tring for it EndsWith
(eturns:
Boolean . ?es@No
)f the -tring EndsWith the $arameter -tring it returns True
)f the -tring doesnt EndsWith the $arameter -tring it return !alse
!or e+ = GThis is a TestG.EndsWith0GTestG1 returns True
GThis is a TestG.EndsWith0GisG1 returns !alse
Exceptions:
ystem.ArgumentNullE-ception = )f the argument is null
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im str #s -tring
str F GVB.NET T$ AD BM-G
)f str.EndsWith0GBM-G1 F True Then
MsgBo+0GThe -tring EndsWith 6BM-6 G1
Else
MsgBo+0GThe -tring does not EndsWith 6BM-6G1
End )f
End -ub
End %lass
When you e+ecute the program you will get a message bo+ li"e GThe -tring EndsWith 6BM-6
G
Strin concat
!oncat in VB.NET -tring %lass using for concat two specified -tring b9ect
ystem.tring.6oncat.ByVal str' As tring3 ByVal str& As tring/ As tring
-tring !oncat method returns a new -tring
Parameters:
-tring strA = $arameter -tring
-tring str5 = $arameter -tring
(eturns:
-tring = # new -tring retrun with strA %oncat with str5
Source code
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
,im strA #s -tring
,im str5 #s -tring
strA F G%oncat01 G
str5 F GTestG
MsgBo+0-tring.%oncat0strA, str511
End -ub
End %las
When you run this source code you will get G%oncat01 Test G in message bo+.
Directory operation
3sing Directory class , we can create , delete , move etc. operations in VB.NET. Because of the
static nature of Directory class , we do not have to instantiate the class. We can call the methods
in the class directly from the Directory class.
4o$ to create a directory Q
)n order to create a new directory , we can call %reate,irectory directly from ,irectory class.
ynta- : Directory.6reateDirectory.Dir2ath/
Dir2ath : The name o$ the ne9 directory
VB.NET = ,irectory.%reate,irectory0Gc=TtestdirG1
4o$ to c%ec0 a directory exist or not Q
Before we creating a directory , we usually chec" that directory e+ist or not. !or that we are
using the E+ists method in the ,irectory class.
ynta- : Directory.E-ists.Dir2ath/ as Boolean
Dir2ath : The name o$ the directory
Boolean : Returns true or $alse 3 i$ directory e-ist it Returns true 3 else it Returns $alse
VB.NET = ,irectory.E+ists0Gc=TtestdirG1
4o$ to mo"e a Directory Q
)f we want to move a directory and its contents from one location to another , we can use the
Move method in the ,irectory class.
ynta- : ,ove.sourceDirName3destDirName/
sourceDirName : The source directory 9e 9ant to move.
destDirName : The destinations directory name.
VB.NET = ,irectory.Move0Gc=TtestdirATtestdir5G, Gc=TtestdirG1
4o$ to delete a Directory Q
When we want to delete a directory we can use the ,elete method in the ,irectory class
ynta- : Delete.Dir2ath/
Dir2ath : The Directory 9e 9ant to delete.
VB.NET = ,irectory.,elete0Gc=TtestdirAG1
The following VB.NET source code shows these operations =
Source code
)mports -ystem.)
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect,E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
)f ,irectory.E+ists0Gc=Ttest,irAG1 Then
6shows message if testdirA e+ist
MsgBo+0G,irectory 6test,ir6 E+ist G1
Else
6create the directory test,irA
,irectory.%reate,irectory0Gc=Ttest,irAG1
MsgBo+0Gtest,irA created O G1
6create the directory test,ir5
,irectory.%reate,irectory0Gc=Ttest,irATtest,ir5G1
MsgBo+0Gtest,ir5 created O G1
6move the directory test,ir5 as test,ir in c= ,irectory.Move0Gc=Ttest,irATtest,ir5G, Gc=Ttest,irG1
MsgBo+0Gtest,ir5 moved G1
6delete the directory test,irA
,irectory.,elete0Gc=Ttest,irAG1
MsgBo+0Gtest,irA deleted G1
End )f
End -ub
End %lass
&ile operation
!ile class is using for the &ile operations in VB.NET. We can create , delete , copy etc. operations
do with &ile class.
4o$ to create a &ile Q
)n order to create a new !ile , we can call %reate method in the !ile class.
ynta- : 4ile.6reate.4ile2ath/
4ile2ath : The name o$ the ne9 4ile 5b?ect
!ile.%reate0Gc=Ttest!ile.t+tG1
4o$ to c%ec0 a &ile exist or not Q
Before we creating a !ile ob9ect , we usually chec" that !ile e+ist or not. !or that we are using
the E+ists method in the !ile class.
ynta- : 4ile.E-ists.4ile2ath/ as Boolean
4ile2ath : The name o$ the 4ile
Boolean : Returns true or $alse 3 i$ 4ile e-ist it Returns true else Returns $alse
VB.NET = !ile.E+ists0Gc=Ttest!ile.t+tG1
The following VB.NET source code shows these operations =

Imports System.I#
Public !lass &orm.
Pri"ate Sub Button./!lic01ByVal sender As System.#b2ect- /
ByVal e As System.E"entArs3 4andles Button..!lic0
I' &ile.Exists16c:Ktest&ile.txt63 T%en
Ts%o$s messae i' test&ile exist
7sBox16&ile Ttest&ileT Exist 63
Else
Tcreate t%e 'ile test&ile.txt
&ile.!reate16c:Ktest&ile.txt63
7sBox16&ile Ttest&ileT created 63
End I'
End Sub
End !lass
When you e+ecute this source code , it first chec" the !ile e+ist or not , )f e+ist it shows message
file e+ist , else it create a new !ile b9ect .
4o$ to !opy a &ile Q
)f we want the %opy of the !ile b9ect we can use the %opy method in !ile class.
ynta- : 6opy.source4ileName3 dest4ileName/
source4ileName : The source $ile 9e 9ant to move.
dest4ileName : The destinations $ile name.
VB.NET = !ile.%opy0Gc=Ttest!ile.t+tG, Gc=Ttest,irTtest!ile.t+tG1
4o$ to delete a &ile #b2ect Q
When we want to delete a !ile b9ect we can use the ,elete methods in the !ile class
ynta- : Delete.4ile2ath/
Dir2ath : The 4ile 5b?ect you 9ant to delete.
VB.NET = !ile.,elete0Gc=Ttest,irTtest!ile.t+tG1
The following VB.NET source code shows these operations =
Source code
)mports -ystem.)
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
)f Not !ile.E+ists0Gc=Ttest!ile.t+tG1 Then
MsgBo+0G!)le not e+ist G1
Else
!ile.%opy0Gc=Ttest!ile.t+tG, Gc=Ttest,irTtest!ile.t+tG1
MsgBo+0G!ile %opied G1
!ile.,elete0Gc=Ttest!ile.t+tG1
MsgBo+0Gfile deleted G1
End )f
End -ub
End %lass
&ile stream
The &ileStream %lass represents a !ile in the %omputer. &ileStream allows to move data to and
from the stream as arrays of bytes. We operate !ile using &ile7ode in &ileStream %lass
Some o' &ile7odes as &ollo$s :
&ile7ode.Append : pen and append to a file , if the file does not e+ist , it create a new file
&ile7ode.!reate : %reate a new file , if the file e+ist it will append to it
&ile7ode.!reateNe$ : %reate a new !ile , if the file e+ist , it throws e+ception
&ile7ode.#pen : pen an e+isting file
4o$ to create a 'ile usin VB.NET &ileStream Q
The following e+ample shows , how to write in a file using !ile-tream.
Source code
)mports -ystem.)
)mports -ystem.Te+t
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
Try
,im w!ile #s -ystem.).!ile-tream
,im byte,ata01 #s Byte
byte,ata F Encoding.#-%)).7etBytes0G!ile-tream TestAG1
w!ile F New !ile-tream0Gstreamtest.t+tG, !ileMode.#ppend1
w!ile.Write0byte,ata, D, byte,ata./ength1
w!ile.%lose01
%atch e+ #s )E+ception
MsgBo+0e+.To-tring1
End Try
End -ub
End %lass
When we e+ecute the program , it create a new &ile and write the content to it .
Text reader
Textreader and TextHriter are the another way to read and write file respectively, even though
these are not stream classes. The Stream(eader and StreamHriter classes are derived from
Text(eader and TextHriter classes respectively.
Source code
)mports -ystem.)
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
Try
,im line #s -tring
,im read!ile #s -ystem.).Te+t2eader F New E
-tream2eader0G%=TTe+t2eader.t+tG1
While True
line F read!ile.2ead/ine01
)f line )s Nothing Then
E+it While
Else
MsgBo+0line1
End )f
End While
read!ile.%lose01
read!ile F Nothing
%atch e+ #s )E+ception
MsgBo+0e+.To-tring1
End Try
End -ub
End %lass
When you e+ecute this program the Text(eader read the file line by line.
Simple text reader
Textreader and TextHriter are the another way to read and write file respectively, even though
these are not stream classes. The Stream(eader and StreamHriter classes are derived from
Text(eader and TextHriter classes respectively. The following program using Te+t2eader ,
2ead the entire content of the file into a -tring
Source code
)mports -ystem.)
$ublic %lass !ormA
$rivate -ub ButtonAE%lic"0ByVal sender #s -ystem.b9ect, E
ByVal e #s -ystem.Event#rgs1 8andles ButtonA.%lic"
Try
,im line #s -tring
,im read!ile #s -ystem.).Te+t2eader F New E
-tream2eader0G%=TTestA.t+tG1
line F read!ile.2eadToEnd01
MsgBo+0line1
read!ile.%lose01
read!ile F Nothing
%atch e+ #s )E+ception
MsgBo+0e+.To-tring1
End Try
End -ub
End %lass
When you e+ecute this program , Text(eader read the entire file in one stretch.
Text $riter
Textreader and TextHriter are the another way to read and write file respectively, even though
these are not stream classes. The Stream(eader and StreamHriter classes are derived from
Text(eader and TextHriter classes respectively. The following sample source showing how
write in a file using TextHriter .
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
'ry
(im )riteFile s System.IO.'e*t+riter , -e) _
Stream+riter(.c/0te*t)riter.t*t.%
)riteFile.+rite1ine(.vb.net2in3ormations.com.%
)riteFile.Flus4(%
)riteFile.Close(%
)riteFile , -ot4in$
Catc4 e* s IO#*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this source code , you will get a file TextHriter.txt and inside it written
"b.net,in'ormations.com
Binary reader
Binary(eader b9ect wor"s at lower level of -treams. Binary(eader is used for read premitive
types as binary values in a specific encoding stream. Binaryreader b9ect wor"s with -tream
b9ects that provide access to the underlying bytes. !or creating a Binary2eader b9ect , you
have to first create a !ile-tream b9ect and then pass Binary2eader to the constructor method .
Dim readtream As 4iletream
readtream # Ne9 4iletream.)c:EtestBinary.dat)3 4ile,ode.5pen/
Dim readBinary As Ne9 BinaryReader.readtream/
The main advantages of Binary information is that stores files as Binary format is the best
practice of space utili:ation.
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im readStream s FileStream
(im ms$ s Strin$
'ry
readStream , -e) FileStream(.c/0testBinary.dat." File5ode.Open%
(im readBinary s -e) Binary6eader(readStream%
ms$ , readBinary.6eadStrin$(%
5s$Bo*(ms$%
readStream.Close(%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
BinaryHriter you can use in the same way to write as binary.
Binary $riter
The BinaryHriter b9ect wor"s at lower level of -treams. BinaryHriter is used for write
premitive types as binary values in a specific encoding stream. BinaryHriter b9ect wor"s with
-tream b9ects that provide access to the underlying bytes. !or creating a BinaryWriter b9ect ,
you have to first create a !ile-tream b9ect and then pass BinaryWriter to the constructor
method .
Dim 9ritetream As 4iletream
9ritetream # Ne9 4iletream.)c:EtestBinary.dat)3 4ile,ode.6reate/
Dim 9riteBinay As Ne9 BinaryDriter.9ritetream/
The main advantages of Binary information is that it is not easily human readable and stores files
as Binary format is the best practice of space utili:ation.
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im )riteStream s FileStream
'ry
)riteStream , -e) FileStream(.c/0testBinary.dat." File5ode.Create%
(im )riteBinay s -e) Binary+riter()riteStream%
)riteBinay.+rite(.'4is is a test 3or Binary+riter 7.%
)riteBinay.Close(%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Binary(eader you can use in the same way to read as binary.
Fmp and bmp 'ile
>$- is an +ml mar"up format that represents a page6s content in Windows $resentation
!oundation vector format. The >$- ,ocument Writer allows you to create .+ps files using any
program that you run on Windows. >$- documents loo" the same in print as they do on the
screen. They are also easy to share because you can view them on any computer where an >$-
viewer is installed, even if the computer does not have the same programs that you used to create
the original documents.
The following VB.NET program convert and +ps document to a bitmap image. %reate a new
VB.NET pro9ect and add a Button to !orm and add the following references to your pro9ect.
7o to $ro9ect.L#dd 2eferences and select these files from .Net tab
windowsbase.dll
ReachFramework.dll
PresentationFramework.dll
PresentationCore.dll
Source code
Imports System
Imports System.IO
Imports System.IO.Packa$in$
Imports System.+indo)s.(ocuments
Imports System.+indo)s.8ps.Packa$in$
Imports System.+indo)s.5edia.Ima$in$
Imports System.Collections.9eneric
Imports System.+indo)s.Forms
Imports System.'e*t
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
'ry
(im *psFile s Strin$ , .c/0Completed2Form.*ps.
*ps'oBmp(*psFile%
5essa$eBo*.S4o)(.(one.%
Catc4 e* s #*ception
5essa$eBo*.S4o)(e*.5essa$e%
#nd 'ry
#nd Sub
Public S4ared Sub *ps'oBmp(ByVal *psFile s Strin$%
(im *ps s -e) 8ps(ocument(*psFile" System.IO.Fileccess.6ead%
(im se:uence s Fi*ed(ocumentSe:uence , *ps.9etFi*ed(ocumentSe:uence(%
For pa$eCount s Inte$er , ; 'o se:uence.(ocumentPa$inator.Pa$eCount 2
1
(im pa$e s (ocumentPa$e ,
se:uence.(ocumentPa$inator.9etPa$e(pa$eCount%
(im toBitmap s -e) 6ender'ar$etBitmap(CInt(pa$e.Si<e.+idt4%"
CInt(pa$e.Si<e.&ei$4t%" =>" =>" System.+indo)s.5edia.Pi*elFormats.?(e3ault@%
toBitmap.6ender(pa$e.Visual%
(im bmp#ncoder s Bitmap#ncoder , -e) BmpBitmap#ncoder(%
bmp#ncoder.Frames.dd(BitmapFrame.Create(toBitmap%%
(im 3Stream s -e) FileStream(.c/0*pstobmp. A pa$eCount A ..bmp."
File5ode.Create" Fileccess.+rite%
bmp#ncoder.Save(3Stream%
3Stream.Close(%
-e*t
#nd Sub
#nd Class
4o$ to create an excel
!rom the following sections you can find how to create an Excel 8>>D wor"sheet through
VB.NET 5DDI. !or creating an Excel 8>>D wor"sheet in VB.NET 5DDI , you have to add the
7icroso't Excel .8.> #b2ect )ibrary in you pro9ect.
!rom the following pictures to show how to add E+cel reference library in your pro9ect.
A. %reate a new pro9ect and add a button to the !orm.
elect re$erence dialouge $rom 2ro?ect menu
elect ,icroso$t E-cel '&.( 5b?ect ;ibrary and clic! 5> button
Now you can start coding to create a new E+cel file.
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect"_
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
*l+orkS4eet.Cells(1" 1% , .4ttp/BBvb.net2in3ormations.com.
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.#*cel 3ile created " you can 3ind t4e 3ile c/0.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
4o$ to open or read
The following sections you can find how to open and edit an Excel 8>>D wor"sheet through
VB.NET 5DDI. !or open or edit an Excel 8>>D wor"sheet in VB.NET 5DDI , you have to add the
7icroso't Excel .8.> #b2ect )ibrary in you pro9ect.
!rom the following pictures to show how to add E+cel reference library in your pro9ect.
A. %reate a new pro9ect and add a button to the !orm.
elect re$erence dialouge $rom 2ro?ect menu
elect ,icroso$t E-cel '&.( 5b?ect ;ibrary and clic! 5> button
Now you can start coding to open or read from E+cel file and edit cells.
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.Open(.c/0test1.*ls*.%
*l+orkS4eet , *l+orkBook.+orks4eets(.s4eet1.%
Ddisplay t4e cells value BE
5s$Bo*(*l+orkS4eet.Cells(E" E%.value%
Dedit t4e cell )it4 ne) value
*l+orkS4eet.Cells(E" E% , .4ttp/BBvb.net2in3ormations.com.
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
In t%e code - Imports Excel 5 7icroso't.#''ice.Interop.Excel , $e assin t%e excel re'erence
to a "atriable Excel.
When you e+ecute this program , the program open the file c=TtestA.+ls+ and edit the content in
the cell B5, it replace the old content to Ghttp=@@vb.net.informations.comG . Before running this
program you have to create an e+cel file name testA.+ls+ and add some data in the cell B5.
4o$ to read entire $or0s%eet in an Excel $or0boo0
)n the following section you can see 8ow to find the last row data in Excel wor"sheet or 8ow to
find the =sed area in a wor"sheet. !or finding last row we are using Hor0S%eet.=sed(ane . )t
will return the last cell . The follwoing code open an Excel file and read the entire content.
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im ran$e s #*cel.6an$e
(im rCnt s Inte$er
(im cCnt s Inte$er
(im Ob! s Ob!ect
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.Open(.c/0vbe*cel.*ls*.%
*l+orkS4eet , *l+orkBook.+orks4eets(.s4eet1.%
ran$e , *l+orkS4eet.Fsed6an$e
For rCnt , 1 'o ran$e.6o)s.Count
For cCnt , 1 'o ran$e.Columns.Count
Ob! , C'ype(ran$e.Cells(rCnt" cCnt%" #*cel.6an$e%
5s$Bo*(Ob!.value%
-e*t
-e*t
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this source code the program read all content from E+cel file.
4o$ to &ormat Excel 8>>D Pae in VB.NET
The following sections you can see , how to do the commonly used format in E+cel 5DDB page.
8ere we enter the data of a Mar" /ist and format the page. !irst we ME27E e+cel cell and
create the heading , then the students name and totals ma"e as B/, . #nd finally create a
border for the whole mar"list part.
#fter you run the source code you will get an E+cel file its loo" li"e in the following picture .
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
(im c4art6an$e s #*cel.6an$e
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
Dadd data
*l+orkS4eet.Cells(G" E% , ..
*l+orkS4eet.Cells(G" H% , .Student1.
*l+orkS4eet.Cells(G" G% , .StudentE.
*l+orkS4eet.Cells(G" I% , .StudentH.
*l+orkS4eet.Cells(I" E% , .'erm1.
*l+orkS4eet.Cells(I" H% , .J;.
*l+orkS4eet.Cells(I" G% , .>I.
*l+orkS4eet.Cells(I" I% , .GI.
*l+orkS4eet.Cells(>" E% , .'ermE.
*l+orkS4eet.Cells(>" H% , .KJ.
*l+orkS4eet.Cells(>" G% , .KE.
*l+orkS4eet.Cells(>" I% , .>;.
*l+orkS4eet.Cells(K" E% , .'ermH.
*l+orkS4eet.Cells(K" H% , .JE.
*l+orkS4eet.Cells(K" G% , .J;.
*l+orkS4eet.Cells(K" I% , .>I.
*l+orkS4eet.Cells(J" E% , .'ermG.
*l+orkS4eet.Cells(J" H% , .KI.
*l+orkS4eet.Cells(J" G% , .JE.
*l+orkS4eet.Cells(J" I% , .>J.
*l+orkS4eet.Cells(=" E% , .'otal.
*l+orkS4eet.Cells(=" H% , .H1I.
*l+orkS4eet.Cells(=" G% , .E==.
*l+orkS4eet.Cells(=" I% , .EHJ.
c4art6an$e , *l+orkS4eet.6an$e(.bE." .eH.%
c4art6an$e.5er$e(%
c4art6an$e.Formula61C1 , .56L 1IS'.
c4art6an$e.&ori<ontalli$nment , H
c4art6an$e.Verticalli$nment , H
c4art6an$e , *l+orkS4eet.6an$e(.bG." .eG.%
c4art6an$e.Font.Bold , 'rue
c4art6an$e , *l+orkS4eet.6an$e(.b=." .e=.%
c4art6an$e.Font.Bold , 'rue
c4art6an$e , *l+orkS4eet.6an$e(.bE." .e=.%
c4art6an$e.Borderround(#*cel.8l1ineStyle.*lContinuous" _
#*cel.8lBorder+ei$4t.*l5edium" #*cel.8lColorInde*. _
*lColorInde*utomatic"#*cel.8lColorInde*.*lColorInde*utomatic%
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.File created 7.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
4o$ to insert a Picture in Excel 8>>D t%rou% proramin on VB.NET 8>>;
The following VB.NET program shows , how to insert a picture in Excel 8>>D . !or inserting a
picture in Excel 8>>D we hav to call the Add2icture method. !or that you have to specify
$ictureName with path , /eft , Top , Width and 8eight.
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
Dadd some te*t
*l+orkS4eet.Cells(1" 1% , .4ttp/BBvb.net2in3ormations.com.
*l+orkS4eet.Cells(E" 1% , .ddin$ picture in #*cel File.
Dreplace you picture to *l_pic.MP9
*l+orkS4eet.S4apes.ddPicture(.C/0*l_pic.MP9." _
5icroso3t.O33ice.Core.5so'riState.msoFalse" _
5icroso3t.O33ice.Core.5so'riState.msoC'rue" I;" I;" H;;" GI%
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.#*cel 3ile created " you can 3ind t4e 3ile c/0.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this program , you will get an E+cel file 0%=Tvbe+cel.+ls+1 with insert the
picture.
4o$ to insert a bac0round Picture in Excel 8>>D t%rou% VB.NET 8>>;
The following VB.NET program shows , how to insert a bac"ground picture in Excel 8>>D . !or
inserting a bac"ground picture in Excel 8>>D we hav to call the etBac!ground2icture mthod in
wor"sheet .
ynta- : etBac!ground2icture.ByVal 4ilename As tring/
4ilename : The bac!ground picture $ilename .
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
Dset back $round
Dreplace your back$round picture to *l_pic.MP9
*l+orkS4eet.SetBack$roundPicture(.C/0*l_pic.MP9.%
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.#*cel 3ile created " you can 3ind t4e 3ile c/0.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this program , you will get an E+cel file 0%=Tvbe+cel.+ls+1 with insert
bac"ground picture.
4o$ to create a !%art in Excel 8>>D in VB.NET
We can create !%art in Excel usin VB.NET 8>>; . The following section shows how to create
a %hart in Excel 8>>D through VB.NET source code .
Before we crate a %hart , we have to fill data in E+cel sheet. #fter enter data your E+cel sheet is
loo" li"e the following picture.
#fter fill the data , We have to create a chart ob9ect in VB.NET and configure the %hart ob9ect
with necressary data li"e positions , si:e , data range , chart type etc..
The following picture shows the e+cel file after created a chart.
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
Dadd data
*l+orkS4eet.Cells(1" 1% , ..
*l+orkS4eet.Cells(1" E% , .Student1.
*l+orkS4eet.Cells(1" H% , .StudentE.
*l+orkS4eet.Cells(1" G% , .StudentH.
*l+orkS4eet.Cells(E" 1% , .'erm1.
*l+orkS4eet.Cells(E" E% , .J;.
*l+orkS4eet.Cells(E" H% , .>I.
*l+orkS4eet.Cells(E" G% , .GI.
*l+orkS4eet.Cells(H" 1% , .'ermE.
*l+orkS4eet.Cells(H" E% , .KJ.
*l+orkS4eet.Cells(H" H% , .KE.
*l+orkS4eet.Cells(H" G% , .>;.
*l+orkS4eet.Cells(G" 1% , .'ermH.
*l+orkS4eet.Cells(G" E% , .JE.
*l+orkS4eet.Cells(G" H% , .J;.
*l+orkS4eet.Cells(G" G% , .>I.
*l+orkS4eet.Cells(I" 1% , .'ermG.
*l+orkS4eet.Cells(I" E% , .KI.
*l+orkS4eet.Cells(I" H% , .JE.
*l+orkS4eet.Cells(I" G% , .>J.
Dcreate c4art
(im c4artPa$e s #*cel.C4art
(im *lC4arts s #*cel.C4artOb!ects
(im myC4art s #*cel.C4artOb!ect
(im c4art6an$e s #*cel.6an$e
*lC4arts , *l+orkS4eet.C4artOb!ects
myC4art , *lC4arts.dd(1;" J;" H;;" EI;%
c4artPa$e , myC4art.C4art
c4art6an$e , *l+orkS4eet.6an$e(.1." .dI.%
c4artPa$e.SetSource(ata(Source/,c4art6an$e%
c4artPa$e.C4art'ype , #*cel.8lC4art'ype.*lColumnClustered
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.#*cel 3ile created " you can 3ind t4e 3ile c/0.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this program you will get the E+cel file with %hart.
4o$ to export a !%art in Excel 8>>D as Picture 'ile 'rom VB.NET
The follwoing program shows how can Export a !%art 'rom Excel 8>>D to Picture 'ile li"e ,
B,2 3 F2< 3 <I4 etc .Before we crate a %hart , we have to fill data in E+cel sheet. #fter enter
data your E+cel sheet is loo" li"e the following picture.
#fter fill the data , We have to create a chart ob9ect in VB.NET and configure the %hart ob9ect
with necressary data li"e positions , si:e , data range , chart type etc.. and use the command for
e+port chart as picture file
The following picture shows the BM$ file e+port from E+cel.
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
Dadd data
*l+orkS4eet.Cells(1" 1% , ..
*l+orkS4eet.Cells(1" E% , .Student1.
*l+orkS4eet.Cells(1" H% , .StudentE.
*l+orkS4eet.Cells(1" G% , .StudentH.
*l+orkS4eet.Cells(E" 1% , .'erm1.
*l+orkS4eet.Cells(E" E% , .J;.
*l+orkS4eet.Cells(E" H% , .>I.
*l+orkS4eet.Cells(E" G% , .GI.
*l+orkS4eet.Cells(H" 1% , .'ermE.
*l+orkS4eet.Cells(H" E% , .KJ.
*l+orkS4eet.Cells(H" H% , .KE.
*l+orkS4eet.Cells(H" G% , .>;.
*l+orkS4eet.Cells(G" 1% , .'ermH.
*l+orkS4eet.Cells(G" E% , .JE.
*l+orkS4eet.Cells(G" H% , .J;.
*l+orkS4eet.Cells(G" G% , .>I.
*l+orkS4eet.Cells(I" 1% , .'ermG.
*l+orkS4eet.Cells(I" E% , .KI.
*l+orkS4eet.Cells(I" H% , .JE.
*l+orkS4eet.Cells(I" G% , .>J.
Dcreate c4art
(im c4artPa$e s #*cel.C4art
(im *lC4arts s #*cel.C4artOb!ects
(im myC4art s #*cel.C4artOb!ect
(im c4art6an$e s #*cel.6an$e
*lC4arts , *l+orkS4eet.C4artOb!ects
myC4art , *lC4arts.dd(1;" J;" H;;" EI;%
c4artPa$e , myC4art.C4art
c4art6an$e , *l+orkS4eet.6an$e(.1." .dI.%
c4artPa$e.SetSource(ata(Source/,c4art6an$e%
c4artPa$e.C4art'ype , #*cel.8lC4art'ype.*lColumnClustered
De*portin$ c4art as picture 3ile
*l+orkS4eet.C4artOb!ects(1%.c4art.#*port(File-ame/, _
.C/0e*cel_c4art_e*port.bmp." Filter-ame/,.B5P.%
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.C4art File #*ported 7.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this program you will get the picture file e+port from E+cel file .
4o$ to Excel 8>>D !%art in VB.NET Picture Box
The follwoing program shows , how to get the Excel c%art as an imae in Picture Box .Before
we crate a %hart , we have to fill data in E+cel sheet. #fter enter data your E+cel sheet is loo"
li"e the following picture.
#fter fill the data , We have to create a chart ob9ect in VB.NET and configure the %hart ob9ect
with necressary data li"e positions , si:e , data range , chart type etc.. and use the command for
e+port chart as picture file , then load the picture from the path to picture bo+
The following picture shows the program screen after drawing the picture
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
Dadd data
*l+orkS4eet.Cells(1" 1% , ..
*l+orkS4eet.Cells(1" E% , .Student1.
*l+orkS4eet.Cells(1" H% , .StudentE.
*l+orkS4eet.Cells(1" G% , .StudentH.
*l+orkS4eet.Cells(E" 1% , .'erm1.
*l+orkS4eet.Cells(E" E% , .J;.
*l+orkS4eet.Cells(E" H% , .>I.
*l+orkS4eet.Cells(E" G% , .GI.
*l+orkS4eet.Cells(H" 1% , .'ermE.
*l+orkS4eet.Cells(H" E% , .KJ.
*l+orkS4eet.Cells(H" H% , .KE.
*l+orkS4eet.Cells(H" G% , .>;.
*l+orkS4eet.Cells(G" 1% , .'ermH.
*l+orkS4eet.Cells(G" E% , .JE.
*l+orkS4eet.Cells(G" H% , .J;.
*l+orkS4eet.Cells(G" G% , .>I.
*l+orkS4eet.Cells(I" 1% , .'ermG.
*l+orkS4eet.Cells(I" E% , .KI.
*l+orkS4eet.Cells(I" H% , .JE.
*l+orkS4eet.Cells(I" G% , .>J.
Dcreate c4art
(im c4artPa$e s #*cel.C4art
(im *lC4arts s #*cel.C4artOb!ects
(im myC4art s #*cel.C4artOb!ect
(im c4art6an$e s #*cel.6an$e
*lC4arts , *l+orkS4eet.C4artOb!ects
myC4art , *lC4arts.dd(1;" J;" H;;" EI;%
c4artPa$e , myC4art.C4art
c4art6an$e , *l+orkS4eet.6an$e(.1." .dI.%
c4artPa$e.SetSource(ata(Source/,c4art6an$e%
c4artPa$e.C4art'ype , #*cel.8lC4art'ype.*lColumnClustered
De*portin$ c4art as picture 3ile
*l+orkS4eet.C4artOb!ects(1%.c4art.#*port(File-ame/, _
.C/0e*cel_c4art_e*port.bmp." Filter-ame/,.B5P.%
Dload t4e pipcture into t4e picture bo*
PictureBo*1.Ima$e , -e) System.(ra)in$.Bitmap _
(.C/0e*cel_c4art_e*port.bmp.%
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.C4art File #*ported 7.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this program you will get the picture in $icture Bo+ from E+cel %hart .
4o$ to Excel 8>>D DataBar in VB.NET
The following program shows , how to do the fre*uenly used 'ormat in Excel 8>>D page. 8ere
we enter the data of a Mar" /ist and format the page. !irst we ME27E e+cel cell and create the
heading , then the students name and totals ma"e as B/, and create a border for the whole
mar"list part. !inally we select the range we want to add DataBar and select the color
#fter you run the source code you will get an E+cel file its loo" li"e in the following picture .
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
(im c4art6an$e s #*cel.6an$e
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
Dadd data
*l+orkS4eet.Cells(G" E% , ..
*l+orkS4eet.Cells(G" H% , .Student1.
*l+orkS4eet.Cells(G" G% , .StudentE.
*l+orkS4eet.Cells(G" I% , .StudentH.
*l+orkS4eet.Cells(I" E% , .'erm1.
*l+orkS4eet.Cells(I" H% , .1;.
*l+orkS4eet.Cells(I" G% , .>I.
*l+orkS4eet.Cells(I" I% , .GI.
*l+orkS4eet.Cells(>" E% , .'ermE.
*l+orkS4eet.Cells(>" H% , .KJ.
*l+orkS4eet.Cells(>" G% , .KE.
*l+orkS4eet.Cells(>" I% , .>;.
*l+orkS4eet.Cells(K" E% , .'ermH.
*l+orkS4eet.Cells(K" H% , .JE.
*l+orkS4eet.Cells(K" G% , .J;.
*l+orkS4eet.Cells(K" I% , .>I.
*l+orkS4eet.Cells(J" E% , .'ermG.
*l+orkS4eet.Cells(J" H% , .KI.
*l+orkS4eet.Cells(J" G% , .JE.
*l+orkS4eet.Cells(J" I% , .=J.
*l+orkS4eet.Cells(=" E% , .'otal.
*l+orkS4eet.Cells(=" H% , .H1I.
*l+orkS4eet.Cells(=" G% , .E==.
*l+orkS4eet.Cells(=" I% , .EHJ.
c4art6an$e , *l+orkS4eet.6an$e(.bE." .eH.%
c4art6an$e.5er$e(%
c4art6an$e.Formula61C1 , .56L 1IS'.
c4art6an$e.&ori<ontalli$nment , H
c4art6an$e.Verticalli$nment , H
c4art6an$e , *l+orkS4eet.6an$e(.bG." .eG.%
c4art6an$e.Font.Bold , 'rue
c4art6an$e , *l+orkS4eet.6an$e(.b=." .e=.%
c4art6an$e.Font.Bold , 'rue
c4art6an$e , *l+orkS4eet.6an$e(.bE." .e=.%
c4art6an$e.Borderround(#*cel.8l1ineStyle.*lContinuous" _
#*cel.8lBorder+ei$4t.*l5edium" #*cel.8lColorInde*. _
ColorInde*utomatic"#*cel.8lColorInde*.*lColorInde*utomatic%
c4art6an$e , *l+orkS4eet.6an$e(.cI." .e=.%
c4art6an$e.FormatConditions.dd(atabar(%
c4art6an$e.FormatConditions(c4art6an$e.FormatConditions.Count% _
.S4o)Value , 'rue
c4art6an$e.FormatConditions(c4art6an$e.FormatConditions.Count%. _
SetFirstPriority(%
c4art6an$e.FormatConditions(1%.BarColor.color , J;>11GE
c4art6an$e.FormatConditions(1%.BarColor.'intndS4ade , ;
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.File created 7.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this program you will get a Mar"/ist with databar
4o$ to Excel 8>>D Data Validation Input 7essae
Data Validation Input 7essaes is using to embed a message in cells in an E+cel -pread -heet.
When we select that cell the message will display . )t is very useful for data entry purpose for
define the rules for entering data and also we can put a notes about the data in the cell. Through
vb.net we can set a Data Validation Input ,essages in E+cel .
The follwong image shows how a ,ata Validation )nput Message after embedded in an E+cel
cell.
Source code
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
(im ran$eCells s #*cel.6an$e
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
*l+orkS4eet.6an$e(.BI." .(I.%.Validation.dd( _
'ype/,#*cel.8l(V'ype.*lValidateInputOnly" _
lertStyle/,#*cel.8l(VlertStyle.*lValidlertStop" _
Operator/,#*cel.8lFormatConditionOperator.*lBet)een%
*l+orkS4eet.6an$e(.BI." .(I.%.Validation.I$noreBlank , 'rue
*l+orkS4eet.6an$e(.BI." .BI.%.Formula61C1 , .Click &ere . N _
.to see -otes.
*l+orkS4eet.6an$e(.BI." .(I.%.Validation.Input'itle , _
.vb.net2in3ormations.com.
*l+orkS4eet.6an$e(.BI." .(I.%.Validation.#rror'itle , .#rror in 'itle.
*l+orkS4eet.6an$e(.BI." .(I.%.Validation.Input5essa$e , .&ere is . N _
. t4e notes embeded 2 you can enter EII c4aracters ma*imum in notes .
*l+orkS4eet.6an$e(.BI." .(I.%.Validation.#rror5essa$e , .#rror in
-otes.
*l+orkS4eet.6an$e(.BI." .(I.%.Validation.S4o)Input , 'rue
*l+orkS4eet.6an$e(.BI." .(I.%.Validation.S4o)#rror , 'rue
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.File created 7.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this source code you can find )nput message in %ell.
4o$ to read data 'rom excel usin #)EDB
Without using E+cel b9ect we can insert , edit , delete , select etc. in cell content of an Excel
8>>D file using #)EDB in VB.NET 8>>; . 8ere we are using le,b%onnection ,
le,b,ata#dapter , ,ata-et for doing these operations in an E+cel file. ?ou have to import
-ystem.,ata in the pro9ect for doing these operations . !or read the content from E+cel file using
ado.net , We can use the SE)E!T command li"e in -P/ perations.
sample -elect s*l
s@l # )select G $rom 7heet'H8)
8ere is the sample E+cel file .
#pen t%e connection usin #)EDB Pro"ider
.provider#,icroso$t.Fet.5;EDB.+.(IData ource#:Jour 4ilename:IE-tended
2roperties#E-cel K.(I/
Speci'y $%ic% data you $ant to read
select G $rom 7heet'H8
8ere is the screen short after reading from E+cel file .
Source code
Imports System.(ata
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
'ry
(im 5yConnection s System.(ata.Ole(b.Ole(bConnection
(im (tSet s System.(ata.(ataSet
(im 5yCommand s System.(ata.Ole(b.Ole(b(atadapter
5yConnection , -e) System.(ata.Ole(b.Ole(bConnection _
(.provider,5icroso3t.Met.O1#(B.G.;O. _
. (ata Source,Dc/0test3ile.*lsDO . _
.#*tended Properties,#*cel J.;O.%
5yCommand , -e) System.(ata.Ole(b.Ole(b(atadapter _
(.select P 3rom ?S4eet1Q@." 5yConnection%
5yCommand.'able5appin$s.dd(.'able." .'est'able.%
(tSet , -e) System.(ata.(ataSet
5yCommand.Fill((tSet%
(ata9ridVie)1.(ataSource , (tSet.'ables(;%
5yConnection.Close(%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
When you e+ecute this program you will get the contents in the e+cel file to the ,ata7rid.
4o$ to insert cell data in an Excel 'ile usin #)EDB
Without using E+cel b9ect we can insert , edit , delete , select etc. in cell content of an Excel
8>>D file using #)EDB in VB.NET 8>>; . 8ere we are using le,b%onnection ,
le,b,ata#dapter , ,ata-et for doing these operations in an E+cel file. ?ou have to import
-ystem.,ata in the pro9ect for doing these operations . !or add new content in the cell or insert a
new content , We can use the INSE(T command li"e in -P/ perations.
sample 3$,#TE s*l
s@l # )Insert into 7heet'H8 .id3name/ values.:0:3:e:/)
The follwoing picture shows before and after update of the -heet.
Source code
Imports System.(ata
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
'ry
(im 5yConnection s System.(ata.Ole(b.Ole(bConnection
(im myCommand s -e) System.(ata.Ole(b.Ole(bCommand
(im s:l s Strin$
5yConnection , -e) System.(ata.Ole(b.Ole(bConnection _
(.provider,5icroso3t.Met.O1#(B.G.;O (ata Source,. N _
.Dc/0test3ile.*lsDO#*tended Properties,#*cel J.;O.%
5yConnection.Open(%
myCommand.Connection , 5yConnection
s:l , .Insert into ?S4eet1Q@ (id"name% values(DID"DeD%.
myCommand.Command'e*t , s:l
myCommand.#*ecute-onCuery(%
5yConnection.Close(%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
5s$Bo*(.6o) dded .%
#nd Sub
#nd Class
When you e+ecute this source code the will insert a row in the E+cel file.
4o$ to update cell data in an Excel 'ile usin #)EDB
Without using E+cel b9ect we can insert , edit , delete , select etc. in cell content of an Excel
8>>D file using #)EDB in VB.NET 8>>; . 8ere we are using le,b%onnection ,
le,b,ata#dapter , ,ata-et for doing these operations in an E+cel file. ?ou have to import
-ystem.,ata in the pro9ect for doing these operations . !or update the content in the cell or
modify the content in a cell , We can use the =PDATE command li"e in -P/ perations.
sample 3$,#TE s*l
s@l # )Lpdate 7heet'H8 set name # :Ne9 Name: 9here id#')
The follwoing picture shows before and after update of the -heet.
Source code
Imports System.(ata
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
'ry
(im 5yConnection s System.(ata.Ole(b.Ole(bConnection
(im myCommand s -e) System.(ata.Ole(b.Ole(bCommand
(im s:l s Strin$
5yConnection , -e) System.(ata.Ole(b.Ole(bConnection _
(.provider,5icroso3t.Met.O1#(B.G.;O (ata Source,. N _
.Dc/0test3ile.*lsDO#*tended Properties,#*cel J.;O.%
5yConnection.Open(%
myCommand.Connection , 5yConnection
s:l , .Fpdate ?S4eet1Q@ set name , D-e) -ameD )4ere id,1.
myCommand.Command'e*t , s:l
myCommand.#*ecute-onCuery(%
5yConnection.Close(%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
5s$Bo*(.Fpdated .%
#nd Sub
#nd Class
When you e+ecute this source code the will update the corrosponding content.
4o$ to export 'rom database to excel
8ere we are going to e+port data from database to E+cel file . We load the data from database to
dataset and then create a new E+cel file and write the data to E+cel file .
!irst step is to /oad the $roduct table data to data set , for detail of $roduct table please refer to
,atabase -tructure .
Ne+t is to create a new E+cel file and write the data from dataset to E+cel file.

For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
l!ork"heet.Cells(i # 1$ j # 1) = %
ds.Tables(0).Rows(i).&tem(j)
'et
'et
Source code
Imports System.(ata
Imports System.(ata.S:lClient
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im cnn s S:lConnection
(im connectionStrin$ s Strin$
(im s:l s Strin$
(im i" ! s Inte$er
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
connectionStrin$ , .data source,servernameO. A _
.initial catalo$,databasenameOuser id,usernameOpass)ord,pass)ordO.
cnn , -e) S:lConnection(connectionStrin$%
cnn.Open(%
s:l , .S#1#C' P F6O5 Product.
(im dscmd s -e) S:l(atadapter(s:l" cnn%
(im ds s -e) (ataSet
dscmd.Fill(ds%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
For ! , ; 'o ds.'ables(;%.Columns.Count 2 1
*l+orkS4eet.Cells(i N 1" ! N 1% , _
ds.'ables(;%.6o)s(i%.Item(!%
-e*t
-e*t
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
cnn.Close(%
5s$Bo*(.Rou can 3ind t4e 3ile C/0vbe*cel.*ls*.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
4o$ to export 'rom Data<ridVie$ to excel
!or e+porting data from ,atagridview to E+cel , connect database and load data from database to
,atagridview and create a new e+cel file and write the data from ,atagridview to E+cel file .
!irst step is to /oad the $roduct table data to ,ata7ridView , for detail of $roduct table please
refer to ,atabase -tructure , and create new E+cel file and write the data from ,atagridview to
E+cel file.
Source code
Imports System.(ata
Imports System.(ata.S:lClient
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im cnn s S:lConnection
(im connectionStrin$ s Strin$
(im s:l s Strin$
connectionStrin$ , .data source,servernameO. A _
.initial catalo$,databasenameOuser id,usernameOpass)ord,pass)ordO.
cnn , -e) S:lConnection(connectionStrin$%
cnn.Open(%
s:l , .S#1#C' P F6O5 Product.
(im dscmd s -e) S:l(atadapter(s:l" cnn%
(im ds s -e) (ataSet
dscmd.Fill(ds%
(ata9ridVie)1.(ataSource , ds.'ables(;%
cnn.Close(%
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles ButtonE.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
(im i s Inte$er
(im ! s Inte$er
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
For i , ; 'o (ata9ridVie)1.6o)Count 2 E
For ! , ; 'o (ata9ridVie)1.ColumnCount 2 1
*l+orkS4eet.Cells(i N 1" ! N 1% , _
(ata9ridVie)1(!" i%.Value.'oStrin$(%
-e*t
-e*t
*l+orkS4eet.Saves(.C/0vbe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
5s$Bo*(.Rou can 3ind t4e 3ile C/0vbe*cel.*ls*.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
Sample Database and tables 'or !rystal (eports tutorials
)n the following section you can see , how to create a sample ,atabase and Tables and data for
running !rystal (eports Tutorials . #ll e+amples in the VB.NET !rystal (eports Tutorials
are based on the following database . !irst we have to create a database . 7ive the database name
as 6crystaldb6
%reate a ,ataBase 6crystaldb6
)n the crystaldb database , create three tables
5rder,aster 3 5rderDetails 3 2roduct .
#rder7aster
5rder,asterMid
5rder,asterMdate
5rder,asterMcustomer
5rder,asterMcreateduser
#rderDetails
5rderDetailsMid
5rderDetailsMmasterid
5rderDetailsMproductid
5rderDetailsM@ty
Product
2roductMid
2roductMname
2roductMprice
The following picture shows the relations of each table =
SR) command 'or creation tables are 'ollo$s :
6REATE TAB;E 7dbo8.75rder,aster8 .
75rder,asterMid8 7int8 N5T NL;; 3
75rder,asterMdate8 7datetime8 NL;; 3
75rder,asterMcustomername8 7varchar8 .0(/3
75rder,asterMcreateduser8 7varchar8 .0(/
/ 5N 72RI,ARJ8
6REATE TAB;E 7dbo8.75rderDetails8 .
75rderDetailsMid8 7int8 N5T NL;; 3
75rderDetailsMmasterid8 7int8 NL;; 3
75rderDetailsMproductid8 7int8 NL;; 3
75rderDetailsM@ty8 7int8 NL;;
/ 5N 72RI,ARJ8
6REATE TAB;E 7dbo8.72roduct8 .
72roductMid8 7int8 N5T NL;; 3
72roductMname8 7varchar8 .0(/ 3
72roductMprice8 7numeric8.'K3 (/ NL;;
/ 5N 72RI,ARJ8
Enter data to the tables =
#rder 7aster Table Data
#rder Details Table Data
Product Table Data
VB.NET !rystal (eports 'rom multiple tables
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
8ere we are going to do is to generate %rystal 2eports from multiple tables. 8ere we have three
table 0ordermaster , orderdetails amd product 1 and we are generating report from these three
tables by connecting each tables with their related fields.
pen Visual -tudio .NET and select a new Visual Basic .NET $ro9ect.
!rom main menu in Visual -tudio select P(#CE!T,,@Add Ne$ Item . Then #dd New )tem
dialogue will appear and select !rystal (eports from the dialogue bo+.
-elect 2eport type from %rystal 2eports gallery.
#ccept the default settings and clic" M.
Ne+t step is to select the appropriate connection to your database. 8ere we are going to select
#)EDB connection 'or SR) Ser"er
-elect /E ,B 0#,1 from %reate New %onnection .
-elect 7icroso't #)E DB Pro"ider 'or SR) Ser"er .
Ne+t screen is the -P/ -erver authentication screen . -elect your -*l Ser"er name , enter userid
- pass$ord and select your Database Name . %lic" ne+t , Then the screen shows /E ,B
$roperty values , leave it as it is , and clic" finish.
Then you will get your -erver name under #)EDB !onnection from there select database name
0%rystaldb1 and clic" the tables , then you can see all your tables from your database.
-elect all table from the table list to right side list bo+, because we are creating report from three
tables 0 rderMaster, rder,etails, $roduct1 .
The ne+t step is to ma"e relation between these selected tables. 8ere we are connecting the
related fields from each table. !or that we arrange the tables in visible area in the list 0this is not
necessary 1 and select the field we are going to ma"e relation and drag to the related field of the
other table. #fter made the relation the screen is loo" li"e the following picture .
Ne+t step is to select the fields from the tables . 8ere we are selecting only %ustomername ,
orderdate from ordermastertable , $roductname from product table and *uantity from order
details.
%lic" the !inish button because now we are not using other functionalities of this wi:ard. #fter
that you will get the %rystal 2eports designer window . ?ou can arrange the fields in the designer
window according to your re*uirement to view the report . !or rearranging you can drag the field
ob9ect in the screen . !or editing right clic" the field ob9ect and select Edit Te+t b9ect. The
following picture shows the sample of designer window after rearrange the field.
Now the designing part is over and the ne+t step is to call the created %rystal 2eports in VB.NET
through !rystal (eports Vie$er control .
-elect the default form 0!ormA.vb1 you created in VB.NET and drag a button and
6rystalReportVie9er control to your form.
-elect !orm6s source code view and put the code on top
Imports 6rystalDecisions.6rystalReports.Engine
$ut the following source code in the button clic" event
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect"
ByVal e s System.#ventr$s% &andles Button1.Click
(im cry6pt s -e) 6eport(ocument
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
#fter you run the source code you will get the report li"e this.
8ere we connected three tables related field and get the result . )f you have any comments please
contact the email address in our contact page.
VB.NET Crystal Reports Integer parameter
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
)n this tutorial we are passing an )nteger $arameter to %rystal 2eports from VB.NET.
)n the previous tutorial , we saw passing a string parameter to %rystal 2eports from VB.NET and
get the result. This is very similar to that tutorial , so here showing only the change information
part only. -o please ta"e a loo" at the complete part of passing a string parameter to %rystal
2eports from VB.NET.
When we pass an )nteger parameter , we have to create a new )nteger parameter in the $arameter
!ields of !ield E+plorer. Then we will get the following screen and fill the fields li"e in the
picture .
#fter creating the parameter field , we have to create the selection formula for the %rystal
2eports . !or creating selection formula , 2ight clic" on %rystal 2eports designer window , select
2E$2T .L -E/E%T)N !2M3/# .L 2E%2, .
Then you can see the record -election !ormula Editor. This for entering the selection formula.
!or that you have to select the fields from above lists and ma"e the formula .
8ere we made the formula li"e select the records from $roduct table whose value is greater than
the input value. !or that first we select the table field that is $roductEprice from $roduct table
and then we select the comparison operator and finally we select our $arameter we created
earlier. ,ouble clic" each field then it will automatically selected
#fter the creation of selection formula close that screen .
Now the designing part is over and the ne+t step is to call the created %rystal 2eports in VB.NET
through !rystal (eports Vie$er control .
-elect the default form 0!ormA.vb1 you created in VB.NET and drag a Te+tbo+ , button and
6rystalReportVie9er control to your form.
-elect !orm6s source code view and import the following =
Imports 6rystalDecisions.6rystalReports.Engine
Imports 6rystalDecisions.hared
$ut the following source code in the button clic" event
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im cry6pt s -e) 6eport(ocument
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
(im crParameterField(e3initions s ParameterField(e3initions
(im crParameterField(e3inition s ParameterField(e3inition
(im crParameterValues s -e) ParameterValues
(im crParameter(iscreteValue s -e) Parameter(iscreteValue
crParameter(iscreteValue.Value , Convert.'oIntHE('e*tBo*1.'e*t%
crParameterField(e3initions , _
cry6pt.(ata(e3inition.ParameterFields
crParameterField(e3inition , _
crParameterField(e3initions.Item(.Price.%
crParameterValues , crParameterField(e3inition.CurrentValues
crParameterValues.Clear(%
crParameterValues.dd(crParameter(iscreteValue%
crParameterField(e3inition.pplyCurrentValues(crParameterValues%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
Now you can run the program . Enter any price , then you can see the report of the $roduct list
whose price is greater than or e*ual to the entered price.
8ere we got the result of $roduct list whose price is grater than ID.
VB.NET Crystal Reports Date parameter
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
)n this tutorial we are passing a date variable to %rystal 2eports from VB.NET.
)n the previous tutorials , we saw passing a string parameter to %rystal 2eports , integer
parameter to %rystal report from VB.NET and get the result. This tutorial is very similar to the
above two tutorials , so please ta"e loo" into the two tutorials before we start this one.
When we pass a ,ate parameter, we have to create a new date parameter in the $arameter !ields
of !ield E+plorer. Then we will get the following screen and fill the fields li"e in the picture .
#fter creating the parameter field , we have to create the selection formula for the %rystal
2eports . !or creating selection formula , 2ight clic" on %rystal 2eports designer window , select
2E$2T .L -E/E%T)N !2M3/# .L 2E%2, .
Then you can see the record -election !ormula Editor. This for entering the selection formula.
!or that you have to select the fields from above lists and ma"e the formula .
8ere we are ma"ing the formula li"e , select all records details from the tables whose order date
is greater than the input date parameter. !or doing this you have to select rdermaster.orderdate ,
comparison operator and parameter date field from selection list of !ormula Editor and ma"e the
formula.
#fter the creation of selection formula close that screen .
Now the designing part is over and the ne+t step is to call the created %rystal 2eports in VB.NET
through !rystal (eport Vie$er control .
-elect the default form 0!ormA.vb1 you created in VB.NET and drag a Te+tbo+ , button and
6rystalReportVie9er control to your form.
-elect !orm6s source code view and import the following =
Imports 6rystalDecisions.6rystalReports.Engine
Imports 6rystalDecisions.hared
$ut the following source code in the button clic" event
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im cry6pt s -e) 6eport(ocument
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
(im crParameterField(e3initions s ParameterField(e3initions
(im crParameterField(e3inition s ParameterField(e3inition
(im crParameterValues s -e) ParameterValues
(im crParameter(iscreteValue s -e) Parameter(iscreteValue
crParameter(iscreteValue.Value , 'e*tBo*1.'e*t
crParameterField(e3initions , _
cry6pt.(ata(e3inition.ParameterFields
crParameterField(e3inition , _
crParameterField(e3initions.Item(.Orderdate.%
crParameterValues , crParameterField(e3inition.CurrentValues
crParameterValues.Clear(%
crParameterValues.dd(crParameter(iscreteValue%
crParameterField(e3inition.pplyCurrentValues(crParameterValues%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
Now you can run the program . Enter any date , then you can see the report whose order date is
greater than or e*ual to the entered date.
8ere we got the result of orders whose date is greater than the entered date
VB.NET Crystal Reports Load Dynamically
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
)n this section we are passing =ser ID - Pass$ord - Ser"er Name and Database Name
dynamically to %rystal 2eports from vb.net .
SIT=ATI#NS :
)n many situations this is useful , for e+ample if you develop a database pro9ect in a test server
and later you have to migrate it , in such situations you have to give these information
dynamically to %rystal 2eports.
)n this program we are using our earlier program and pass the values dynamically to %rystal
2eports. Before we start this section ta"e a loo" at the step by step %rystal 2eport in VB.NET .
)n the step by step %rystal 2eport we created a report selecting all data from the $roduct table .
There is no chance to change the server on runtime in that case because it is a static report . 8ere
we are passing -erver Name , 3ser), and $assword dynamically to the %rystal 2eports.
8ere we use %rystal 2eports !onnectionIn'o .
Dim cr6onnectionIn$o As Ne9 6onnectionIn$o , and pass these arguments to %onnection)nfo
-elect the default form 0!ormA.vb1 you created in VB.NET and drag a button and
6rystalReportVie9er control to your form.
-elect !orm6s source code view and import the following =
Imports 6rystalDecisions.6rystalReports.Engine
Imports 6rystalDecisions.hared
$ut the following source code in the button clic" event
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im cry6pt s -e) 6eport(ocument
(im crtable1o$onin3os s -e) 'able1o$OnIn3os
(im crtable1o$onin3o s -e) 'able1o$OnIn3o
(im crConnectionIn3o s -e) ConnectionIn3o
(im Cr'ables s 'ables
(im Cr'able s 'able
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
+it4 crConnectionIn3o
.Server-ame , .ROF6 S#6V#6 -5#.
.(atabase-ame , .ROF6 ('BS# -5#.
.FserI( , .ROF6 ('BS# FS#6-5#.
.Pass)ord , .ROF6 ('BS# PSS+O6(.
#nd +it4
Cr'ables , cry6pt.(atabase.'ables
For #ac4 Cr'able In Cr'ables
crtable1o$onin3o , Cr'able.1o$OnIn3o
crtable1o$onin3o.ConnectionIn3o , crConnectionIn3o
Cr'able.pply1o$OnIn3o(crtable1o$onin3o%
-e*t
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
?ou have to replace the source code values of )J5LR ERVER NA,E) 3 )J5LR
DATABAE NA,E) 3 )J5LR DATABAE LERNA,E) 3 )J5LR DATABAE
2AD5RD) with your correct values .
When you run this program you will get the following screen.
VB.NET Crystal Reports Formula Fields
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
)n this tutorial we are adding a &ormula &ield in e+isting %rystal 2eports .
SIT=ATI#NS :
)f you have a %rystal 2eports with Pty and $rice , you need an additional field in your %rystal
2eports for the Total of ATJ N 2RI6E . )n this situation you have to use the &ormula &ield in
%rystal 2eports.
)n this tutorial we are showing the all orders with *ty and price and the total of each row , that
means each in each row we are showing the total of *ty and price. Before starting this tutorial.
%reate a new %rystal 2eports with fields %ustomerName , rder ,ate , $roduct Name and
$roduct $rice . )f you do not "now how to create this report , 9ust loo" the previous tutorial
%rystal 2eport from multiple tables . )n that report selecting only four fields , here we need one
more field $rodcut.L$rice .
#fter you create the %rystal 2eports you screen is loo" li"e the following picture =
Ne+t is to create the a &ormula &ield for showing the total of Pty and $rice .
2ight %lic" &ormula &ield in the !ield E+plorer and clic" New. Then you will get an )nput
Message Bo+ , type Total in te+tbo+ and clic" 3se Editor
Now you can see !ormula Editor screen . Now you can enter which formula you want . 8ere we
want the result of Aty N 2rice . !or that we select rder,etails.Pty , the multiplication operator
and $roduct.$rice . ,ouble clic" each field for selection.
Now you can see Total 3nder the &ormula &ield . ,rag the field in to the %rystal 2eports where
ever you want .
Now the designing part is over . -elect the default form 0!ormA.vb1 you created in VB.NET and
drag a button and 6rystalReportVie9er control to your form.
-elect !orm6s source code view and import the following =
Imports 6rystalDecisions.6rystalReports.Engine
$ut the following source code in the button clic" event
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im cry6pt s -e) 6eport(ocument
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
When you run this program you will get the following screen.
VB.NET Crystal Reports Summary Fields
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
)n this tutorial we are ta"ing the sum of field value of Total . This is the continuation of the
previous tutorial %rystal 2eport !ormula !ield . -o before we start this tutorial , ta"e a loo" at
the previous tutorial %rystal 2eport !ormula !ield.
8ere we are ta"ing the grand total of the Total field . The Total field is a !ormula field is the
result of *ty > price .
)n the %rystal 2eports designer view right clic" on the 2eport !ooter , 9ust below the Total field
and select )nsert .L -ummary .
Then you will get a screen , select the Total from the combo bo+ and -um from ne+t %ombo Bo+
, and summary location 7rand Total 02eport !ooter1 . %lic" " button
Now you can see UTotal is 9ust below the Total field in the report !ooter.
Now the designing part is over . -elect the default form 0!ormA.vb1 you created in VB.NET and
drag a button and 6rystalReportVie9er control to your form.
-elect !orm6s source code view and import the following =
Imports 6rystalDecisions.6rystalReports.Engine
$ut the following source code in the button clic" event
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im cry6pt s -e) 6eport(ocument
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
When you run this program you will get the following screen.
VB.NET Crystal Reports Export to DF
E+porting from !rystal (eports to PD& 'ormat , we are using %rystal 2eportss
6rE-port5ptions . #lso we have to set 2d$Rt$Dord4ormat5ptions and
E-port4ormatType.2ortableDoc4ormat . )n the following e+ample you can see how to e+port a
%rystal 2eports as a $,! format file.
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
)n this tutorial we are using our earlier program step by step %rystal 2eport for pull data from
database to %rystal 2eports . Before we start this section ta"e a loo" at the step by step %rystal
2eport in VB.NET .
)n the step by step %rystal 2eport we pull all data from $roduct table , here now we are e+porting
that data to a $,! format file.
-elect the default form 0!ormA.vb1 you created in VB.NET and drag two buttons 0ButtonA,
Button5 1 and 6rystalReportVie9er control to your form.
-elect !orm6s source code view and import the following =
Imports 6rystalDecisions.6rystalReports.Engine
$ut the following source code in the button clic" events
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
(im cry6pt s -e) 6eport(ocument
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles ButtonE.Click
'ry
(im Cr#*portOptions s #*portOptions
(im Cr(iskFile(estinationOptions s -e) _
(iskFile(estinationOptions(%
(im CrFormat'ypeOptions s -e) Pd36t3+ordFormatOptions(%
Cr(iskFile(estinationOptions.(iskFile-ame , _
.c/0crystal#*port.pd3.
Cr#*portOptions , cry6pt.#*portOptions
+it4 Cr#*portOptions
.#*port(estination'ype , #*port(estination'ype.(iskFile
.#*portFormat'ype , #*portFormat'ype.Portable(ocFormat
.(estinationOptions , Cr(iskFile(estinationOptions
.FormatOptions , CrFormat'ypeOptions
#nd +it4
cry6pt.#*port(%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
When you run this program you will get the $,! file 0crystalE+port.pdf1 in your computer6s %=
VB.NET Crystal Reports Export to Excel
E+porting from !rystal (eports to Excel 'ormat , we are using %rystal 2eports
6rE-port5ptions . #lso we have to set E-cel4ormat5ptions and E-port4ormatType.E-cel . )n
the following e+ample you can see how to e+port a %rystal 2eports as a E+cel format file.
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
)n this tutorial we are using our earlier program step by step %rystal 2eport pull data from
database to %rystal 2eports . Before we start this section ta"e a loo" at the step by step %rystal
2eport in VB.NET .
)n the step by step %rystal 2eport we pull all data from $roduct table , here now we are e+porting
that data to a E+cel format file.
-elect the default form 0!ormA.vb1 you created in VB.NET and drag two buttons 0ButtonA,
Button5 1 and 6rystalReportVie9er control to your form.
-elect !orm6s source code view and import the following =
Imports 6rystalDecisions.6rystalReports.Engine
$ut the following source code in the button clic" events
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
(im cry6pt s -e) 6eport(ocument
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles ButtonE.Click
'ry
(im Cr#*portOptions s #*portOptions
(im Cr(iskFile(estinationOptions s -e) _
(iskFile(estinationOptions(%
(im CrFormat'ypeOptions s -e) #*celFormatOptions
Cr(iskFile(estinationOptions.(iskFile-ame , _
.c/0crystal#*port.*ls.
Cr#*portOptions , cry6pt.#*portOptions
+it4 Cr#*portOptions
.#*port(estination'ype , #*port(estination'ype.(iskFile
.#*portFormat'ype , #*portFormat'ype.#*cel
.(estinationOptions , Cr(iskFile(estinationOptions
.FormatOptions , CrFormat'ypeOptions
#nd +it4
cry6pt.#*port(%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
When you run this program you will get the E+cel file 0crystalE+port.+ls1 in your computer6s %=
Email a Crystal Reports !rom VB.NET
!or Email a !rystal (eports , we have to e+port the %rystal 2eports in any of the !ile !ormat
available in %rystal 2eports and then Email it.
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
)n this tutorial we use the tutorial E+port %rystal 2eport to $,! file . -o before we start this
section please ta"e a loo" at the tutorial E+port %rystal 2eport to $,! file
#fter e+port the %rystal 2eports as a $,! file , the ne+t step is to email that file . !or that here
we are using ystem.Deb.,ail . We have to provide the necessary information to configuring
mtp,ail client and send the e+ported file as attachment .
-elect the default form 0!ormA.vb1 you created in VB.NET and drag two buttons 0ButtonA,
Button5 1 and 6rystalReportVie9er control to your form.
-elect !orm6s source code view and import the following =
Imports 6rystalDecisions.6rystalReports.Engine
Imports 6rystalDecisions.hared
Imports ystem.Deb.,ail
$ut the following source code in the button clic" events
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Imports System.+eb.5ail
Public Class Form1
(im cry6pt s -e) 6eport(ocument
(im pd3File s Strin$ , .c/0Product6eport1.pd3.
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles ButtonE.Click
'ry
(im Cr#*portOptions s #*portOptions
(im Cr(iskFile(estinationOptions s -e) _
(iskFile(estinationOptions(%
(im CrFormat'ypeOptions s -e) Pd36t3+ordFormatOptions
Cr(iskFile(estinationOptions.(iskFile-ame , pd3File
Cr#*portOptions , cry6pt.#*portOptions
+it4 Cr#*portOptions
.#*port(estination'ype , #*port(estination'ype.(iskFile
.#*portFormat'ype , #*portFormat'ype.Portable(ocFormat
.(estinationOptions , Cr(iskFile(estinationOptions
.FormatOptions , CrFormat'ypeOptions
#nd +it4
cry6pt.#*port(%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
send5ail(%
#nd Sub
Private Sub send5ail(%
'ry
(im Smtp s Smtp5ail
Smtp5ail.SmtpServer.Insert(;" .your 4ostname.%
(im 5s$ s 5ail5essa$e , -e) 5ail5essa$e
5s$.'o , .to address 4ere.
5s$.From , .3rom address 4ere.
5s$.Sub!ect , .Crystal 6eport ttac4ment .
5s$.Body , .Crystal 6eport ttac4ment .
5s$.ttac4ments.dd(-e) 5ailttac4ment(pd3File%%
Smtp.Send(5s$%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
N#TES:
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
Before you run this programme , you have to provide the necessary ,T2 informations , that is
your =5TNA,E 3 4R5, ADDRE and T5 ADDRE to the -MT$ client.
Crystal Reports "it#out Data$ase
3sually !rystal (eports we are using to fetch data from database and show it as a report. 8ere
we are going to generate a %rystal 2eports without using a datbase . !or generating a %rystal
2eports without database , here we are using a -trongly Typed ,ataset and a ,ata Table.
The basics of !rystal (eports creation you can find in the previous section of this tutorial ,
before we start this tutorial you can ta"e a loo" at the step by step %rystal 2eport.
<eneratin a Stronly Typed DataSet
%reate a new VB.NET $ro9ect and accept the default settings. %reate a new ,ataset from $ro9ect
. #dd New )tem ,ialogue Bo+.
#ccept the default name ,ata-etA.+sd .
!reate a data table 'or DataSet..xsd .
-elect ,ata-etA.+sd from -olution E+plorer and right clic" . -elect datatable from the menu.
Then you will get a datatable in the ,atast . 2ight clic" the datatable and select #dd.%olumn .
8ere we are ma"ing a two column %rystal 2eports , so we need two column in the data table .
#dd and ), column and Name column in the ,ata Table.
Now the dataset part is over . Ne+t step is to create a %rystal 2eports from this ,ataset . Before
going to ma"e %rystal 2eports design please ta"e a loo" at step by step %rystal 2eport for easy
creation of %rystal 2eports.
-elect a new %rystal 2eports from #dd New )tem menu and accept the default settings. The ne+t
screen is to select appropriate data source . There you can find the ,atatableA from $ro9ect data .
#,.NET ,atasets , and select ,atatableA to the right side.
%lic" Ne+t button and select ), and Name from the datatableA to right side and clic" finish.
Now the %rystal 2eports designer part is over . Ne+t part is to create data for the %rystal
2eports . !or that we have to create a ,ata Table through programmatically and add data to
datasetA.
-elect the default form 0!ormA.vb1 you created in VB.NET and drag one button and
6rystalReportVie9er control to your form.
$ut the following source code in the button clic" events
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Imports System.(ata
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im ds s -e) (ataSet1
(im t s (ata'able , ds.'ables.dd(.Items.%
t.Columns.dd(.id." 'ype.9et'ype(.System.IntHE.%%
t.Columns.dd(.Item." 'ype.9et'ype(.System.Strin$.%%
(im r s (ata6o)
(im i s Inte$er
For i , ; 'o =
r , t.-e)6o)(%
r(.id.% , i
r(.Item.% , .Item. A i
t.6o)s.dd(r%
-e*t
(im ob!6pt s -e) Crystal6eport1
ob!6pt.Set(ataSource(ds.'ables(1%%
Crystal6eportVie)er1.6eportSource , ob!6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
Crystal Reports !rom S%L %uery String
We can create %rystal 2eports in VB.NET using -P/ Puery -tring . 8ere we create a -trongly
Typed dataset for %rystal 2eports design and create a connection ob9ect and e+ecute the -P/
Puery -tring .
#ll !rystal (eport programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
The basics of !rystal (eports creation you can find in the previous section of this tutorial ,
before we start this tutorial you can ta"e a loo" at the step by step %rystal 2eport.
<eneratin a Stronly Typed DataSet
)n the previous section you can see a detailed tutorial about to create a strongly typed datset and
its %rystal 2eports design . #fter create the dataset and %rystal 2eports design you should create
a connection ob9ect and fetch the data from database.
-elect the default form 0!ormA.vb1 you created in VB.NET and drag one button and
6rystalReportVie9er control to your form.
$ut the following source code in the button clic" events
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Imports System.(ata
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im ds s -e) (ataSet1
(im cnn s S:lConnection
(im connectionStrin$ s Strin$
(im s:l s Strin$
connectionStrin$ , .data source,servernameO _
initial catalo$,crystaldbOuser id,usernameOpass)ord,pass)ordO.
cnn , -e) S:lConnection(connectionStrin$%
cnn.Open(%
s:l , .S#1#C' Product_id"Product_name"Product_price F6O5 Product.
(im dscmd s -e) S:l(atadapter(s:l" cnn%
(im ds s -e) (ataSet1
dscmd.Fill(ds" .Product.%
5s$Bo*(ds.'ables(1%.6o)s.Count%
cnn.Close(%
(im ob!6pt s -e) Crystal6eport1
ob!6pt.Set(ataSource(ds.'ables(1%%
Crystal6eportVie)er1.6eportSource , ob!6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
N#TE :
?ou have to provide the necessary databse information to %onnection -tring.
Crystal Reports !rom S%L %uery String
)n usual practice , %rystal 2eports we are getting from pre defined columns. But we can ma"e
%rystal 2eports from ,ynamic column . 8ere we are going to do the dynamic %rystal 2eports
from -P/ statements . That is we enter -P/ in te+tbo+ and get the %rystal 2eports according to
the -P/ statement.
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
%reate a new VB.NET pro9ect and add a -trongly Typed ,ataset . Before creating a -trongly
Typed ta"e a loo" at the detailed tutorial of create a strongly typed datset and add five column in
the ,atatable. 8ere we are limiting as five column , but you can add any number of column
according to your re*uirements.
Ne+t step is to create a %rystal 2eports design from the -trongly Typed dataset.
-elect all the column from dataset.
-elect the default form0!ormA.vb1 and add a Te+tBo+ , Button and %rystal 2eports Viewer .
8ere we are going to pass the -Pl statements to %rystal 2eports at runtime . !or that we parsing
the -P/ statement before we passing it to %rystal 2eports. -o we create a function for parsing
-P/ statements.
2ublic 4unction procesA;./ As tring
$ut the following vb.net source code in your form and run the program .
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Imports System.(ata
Public Class Form1
(im ob!6pt s -e) Crystal6eport1
Private Sub Button1_Click(ByVal sender s System.Ob!ect"
ByVal e s System.#ventr$s% &andles Button1.Click
(im cnn s S:lConnection
(im connectionStrin$ s Strin$
(im s:l s Strin$
connectionStrin$ , .data source,S#6V#6-5#O _
initial catalo$,crystaldbOuser id,saOpass)ord,PSS+O6(O.
cnn , -e) S:lConnection(connectionStrin$%
cnn.Open(%
s:l , procesSC1(%
(im dscmd s -e) S:l(atadapter(s:l" cnn%
(im ds s -e) (ataSet1
dscmd.Fill(ds" .Product.%
ob!6pt.Set(ataSource(ds.'ables(1%%
Crystal6eportVie)er1.6eportSource , ob!6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
Public Function procesSC1(% s Strin$
(im s:l s Strin$
(im inS:l s Strin$
(im 3irstPart s Strin$
(im lastPart s Strin$
(im selectStart s Inte$er
(im 3romStart s Inte$er
(im 3ields s Strin$(%
(im i s Inte$er
(im 5y'e*t s 'e*tOb!ect
inS:l , 'e*tBo*1.'e*t
inS:l , inS:l.'oFpper
selectStart , inS:l.Inde*O3(.S#1#C'.%
3romStart , inS:l.Inde*O3(.F6O5.%
selectStart , selectStart N >
3irstPart , inS:l.Substrin$(selectStart" (3romStart 2 selectStart%%
lastPart , inS:l.Substrin$(3romStart" inS:l.1en$t4 2 3romStart%
3ields , 3irstPart.Split(.".%
3irstPart , ..
For i , ; 'o 3ields.1en$t4 2 1
I3 i S ; '4en
3irstPart , 3irstPart A . " . _
A 3ields(i%.'oStrin$(% A . S CO1F5-. A i N 1
5y'e*t , C'ype(ob!6pt.6eport(e3inition.6eportOb!ects(.'e*t. _
A i N 1%" 'e*tOb!ect%
5y'e*t.'e*t , 3ields(i%.'oStrin$(%
#lse
3irstPart , 3irstPart A 3ields(i%.'oStrin$(% A _
. S CO1F5-. A i N 1
5y'e*t , C'ype(ob!6pt.6eport(e3inition.6eportOb!ects(.'e*t. A
_
i N 1%" 'e*tOb!ect%
5y'e*t.'e*t , 3ields(i%.'oStrin$(%
#nd I3
-e*t
s:l , .S#1#C' . A 3irstPart A . . A lastPart
6eturn s:l
#nd Function
#nd Class
N#TE :
?ou have to provide the necessary databse information to %onnection -tring.
Crystal Reports !rom &'L File
)n this section you can see , creating a %rystal 2eports from >M/ file instead of database . This
is very similer to creating %rystal 2eports from database , the only difference is to sslect the data
source as your >M/ file.
8ere we are creating an >M/ file name is $roduct is >M/ file the same structure of the $roduct
table in the sample ,atabase -tructure.
,ownload $roduct.>M/
The basics of %rystal 2eports creation provided in previous tutorials , if you dont have much
"nowledge in %rystal 2eports , ta"e a loo" at the tutorial step by step %rystal 2eport before start
this section.
The change happen only from previous report , when you select ,ata for %rsyatl 2eport , you
have to select 6reate Ne9 6onnection O Database 4iles and select the >M/ file you want to
generate %rystal 2eports 0)n this case you select the $roduct.+ml 1.
-elect all the fields from $roduct and clic" finish button
Now the designer part is over . Ne+t step is to select the default form0!ormA.vb1 and add a
Button and %rystal 2eports Viewer to the !orm.
$ut the following vb.net source code in your form and run the program .
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im cry6pt s -e) 6eport(ocument
cry6pt.1oad(.PF' C6RS'1 6#PO6' P'& &#6#0Crystal6eport1.rpt.%
Crystal6eportVie)er1.6eportSource , cry6pt
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
cry2pt./oad0G$3T %2?-T#/ 2E$2T $#T8 8E2ET%rystal2eportA.rptG1
The %rystal 2eport is in your pro9ect location, there you can see !rystal(eport..rpt . -o give
the full path name of report here.
Create a Su$report in Crystal Reports
-ubreport in %rystal 2eports means a 2eport within a 2eport . When we want to show some
additional information about the data in the %rystal 2eports , we use the subreports to show the
details. -ubreports we show within the main %rystal 2eports and also we can show it as n.
,emand report , that means we put an 8yper lin" in the row, and when user clic" that hyper lin"
then will get the subreport.
This section we are showing the subreport within the %rystal 2eports . That is for each row there
is a subreoprt for the details.
#ll !rystal (eports programming samples in this tutorials is based on the following database
0crystaldb1 . $lease ta"e a loo" at the database structure before you start this tutorial . %lic" here
to see ,atabase -tructure .
8ere we are create an order report based on three tables in the database and show a subreoprt for
each row of the specified $roduct Name. 8ere we are using our earlier program %rystal 2eport
from multiple tables to show the main %rystal 2eports ,ata , so please refer %rystal 2eport from
multiple tables before start this section .
%reate a %rystal 2eports using three tables and select customername , date , product and *ty . )t
will e+plain in detail the previous section %rystal 2eport from multiple tables .
Ne+t step is to create a subreport inside the main report. 8ere we are showing the $roduct details
in each row of the specified product in the main row.
#fter create the main report , right clic" on %rystal 2eports designer window and select )nsert.
-ubreport.
Then you will get the subreport ob9ect , drag the ob9ect in the designer window at the down part
of the details tab , 9ust below the fields in the details tab. When you release the mouse you will
get a dialogue bo+ as"ing report name . Enter the report name you want and clic" the 2eport
Wi:ard button.
The wi:ard shows the table selection screen and select the table . 8ere in this case we are
selecting the $roduct Table from the list and clic" ne+t .
Ne+t screen is showing the table , from there select the fields you want to show the data and clic"
finish. The you will get the subreport main screen again and select /in" tab .
The lin" tab is ma"ing relation with your main 2eport and subreport . 8ere we are lin"ing the
productname from main report to the subreport. !or that select $roduct.$roductEname from
#vailable fields.
#ccept the other settings as it is in the screen and clic" o". Now you can see the subreport ob9ect
in the screen , if you want to modify subreport design , double clic" on subreport ob9ect and you
can design subreport.
Now the designer part is over . Ne+t step is to select the default form0!ormA.vb1 and add a
Button and %rystal 2eports Viewer to the !orm.
$ut the following vb.net source code in your form and run the program .
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im crp s -e) Crystal6eport1
Crystal6eportVie)er1.6eportSource , crp
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
Create a Su$report in Crystal Reports (it# Lin)
)n the previous section -ubreport in %rystal 2eport is described how to insert a subreport in
%rystal 2eports . )n that case the subreport is embedded within the main %rystal 2eports. 8ere
we are creating a subreport , and the subreport has only a lin" in the main 2eport , on.demand
subreports . That is when the user clic" the lin" , then only the subreport display.
8ere we are using our previous e+ample -ubreport in %rystal 2eport and ma"e a lin" in the min
%rystal 2eports for on.demand subreport.
-elect the subreport ob9ect in the %rystal 2eports and right clic" , then select !ormat b9ect .
Then you will get !ormat Editor . -elect -ubreport tab from !ormat Editor , you can find there a
chec" bo+ n.demand -ubreport . ?ou have to select that chec" bo+ , then the subreport become
as a lin" in your main %rystal 2eports. )f you want to change the title , you can change it in
subreport name te+tbo+. !inally clic" M button.
Now the designing part is over and you are ready to generate subreport on.demand. Ne+t step is
to select the default form0!ormA.vb1 and add a Button and %rystal 2eport Viewer to the !orm.
$ut the following vb.net source code in your form and run the program .
Do$nload Source !ode
Print Source !ode
Imports Crystal(ecisions.Crystal6eports.#n$ine
Imports Crystal(ecisions.S4ared
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im crp s -e) Crystal6eport1
Crystal6eportVie)er1.6eportSource , crp
Crystal6eportVie)er1.6e3res4(%
#nd Sub
#nd Class
*o( to deploy Crystal Reports on Clinet 'ac#ine
!rystal (eports for Visual -tudio ships with your deployment pro9ects that enable you to
deploy %rystal 2eports components and assemblies on the target machine. We can use different
approaches to install %rystal 2eports runtime files on the target machine .
)f you are using Visual -tudio then during your setup and deployment you can add the
6RRedist&((0M-K1.msi file to your setup file and distribute it as a single setup file . The installer
can e+ecute the setup file automatically with your .Net $ro9ect in a single clic". ?ou can find the
6RRedist&((0M-K1.msi file in your system6s !:KProram &ilesK7icroso't Visual Studio
AKSDMK"8.>KBootStrapperKPac0aesK!rystal(eports . #lso you can distribute the
6RRedist&((0M-K1.msi separately and install it on the target machine.
The other way to install %rystal 2eports on target machine is to create a setup file using 7ere
7odules and distribute it with your application or as a separate setup file. %lic" the following
lin" to see how to ma"e a setup file with Merge Modules.
%rystal 2eports installer using Merge Modules.
*o( to create Crystal Reports installer using
'erge 'odules
!rystal (eports uses merge modules to ensure the correct report components and assemblies are
installed with your deployment pro9ect. # merge module is a set of components that are merged
with a Windows installer for applications that need them. The following steps are creating a
setup file for %rystal 2eports %lient side installation using Merge Modules.
Before creating a setup pro9ect, ma"e sure that the following files e+ist in the KProram
&ilesK!ommon &ilesK7ere 7odules folder.
6rystalReportsRedist&((0M-K1.msm
,icroso$tMV6K(MAT;M-K1.msm
policyMKM(M,icroso$tMV6K(MAT;M-K1.msm
Steps to create Setup 'ile.
A1 Ma"e sure the above mentioned files are in the KProram &ilesK!ommon &ilesK7ere
7odules folder , )f the files are not there you can download the file and copy it to the folder
KProram &ilesK!ommon &ilesK7ere 7odules .
,ownload= https=@@www.sdn.sap.com@ir9@scn@weblogsVblogF@pub@wlg@AA;CC
51 pen your Visual -tudio
41 -elect GNew $ro9ectG from !ile menu.
<1 -elect G-etup and ,eploymentG from Gther $ro9ect TypesG
I1 )n the G-olution E+plorerG, select your setup pro9ect, right.clic", and select #dd and Merge
Module from the menu.
;1 -elect 6rystalReportsRedist&((0M-K1.msm to your setup pro9ect.
The file available at T$rogram !ilesT%ommon !ilesTMerge Modules
Then you can see ,icroso$tMV6K(MAT;M-K1.msm and
policyMKM(M,icroso$tMV6K(MAT;M-K1.msm will be automatically added in the ,etected
,epencies section.
B1 Build your pro9ect.
Now you will get the setup file for distribution. Either you can add this setup file to you
application installer or distribute it as a separate setup file.
*o( to send email !rom VB.NET
VB.NET using S7TP protocol for sending email . -MT$ stands for Simple 7ail Trans'er
Protocol . VB.NET using ystem.Net.,ail namespace for send mail . We can instantiate
mtp6lient class and assign the =ost and 2ort . The default port using -MT$ is 8; , but it may
vary different Mail -ervers .)n the following e+ample shows how to send an email from a 7mail
address.
The 7mail -MT$ server name is smtp.gmail.com and the port using send mail is 0KP . 8ere
using Net9or!6redential for password based authentication.
Do$nload Source !ode
Print Source !ode
Imports System.-et.5ail
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
'ry
(im SmtpServer s -e) SmtpClient(%
(im mail s -e) 5ail5essa$e(%
SmtpServer.Credentials , -e) _
-et.-et)orkCredential(.usernameT$mail.com." .pass)ord.%
SmtpServer.Port , IJK
SmtpServer.&ost , .smtp.$mail.com.
mail , -e) 5ail5essa$e(%
mail.From , -e) 5ailddress(.ROF6usernameT$mail.com.%
mail.'o.dd(.'O((6#SS.%
mail.Sub!ect , .'est 5ail.
mail.Body , .'4is is 3or testin$ S5'P mail 3rom 95I1.
SmtpServer.Send(mail%
5s$Bo*(.mail send.%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
?ou have to provide the informations li"e your gmail username and password , and the to
address also.
VB.NET Send email using CD+S,S
3sing !D#SYS is another easy way to send email from VB.NET . !or sending email using
%,-?- , you have to send email from Dindo9s &(((QN2 and also you have to be enabled
,T2 ervice in ))- .
(eSuirements

!indows (P) !indows*000
&nternet &n+ormation "er,ices (&&")
"-TP "er,ices in &&" should be enable.
Do$nload Source !ode
Print Source !ode
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect"
ByVal e s System.#ventr$s% &andles Button1.Click
(im C(OSRS s Ob!ect
Const cdoSendFsin$Pickup , 1
Const strPickup , .c/0inetpub0mailroot0pickup.
C(OSRS , CreateOb!ect(.C(O.5essa$e.%
C(OSRS.Con3i$uration.Fields.item _
(.4ttp/BBsc4emas.microso3t.comBcdoBcon3i$urationBsendusin$.% _
, cdoSendFsin$Pickup
C(OSRS.Con3i$uration.Fields.item _
(.4ttp/BBsc4emas.microso3t.comBcdoBcon3i$uration. A _
Bsmtpserverpickupdirectory.% _
, strPickup
C(OSRS.Con3i$uration.Fields.Fpdate(%
C(OSRS.'o , .'O ((6#SS.
C(OSRS.From , .F6O5 ((6#SS.
C(OSRS.Sub!ect , .C(O 'est.
C(OSRS.'e*tBody , .Send #mail 3rom vb.net usin$ C(OSRS.
C(OSRS.Send(%
C(OSRS , -ot4in$
5s$Bo*(.mail send.%
#nd Sub
#nd Class
?ou have to provide the informations li"e To Address 3 4rom Address and it is very important to
enable your ,T2 services in II .
*o( to -nd I .ddress o! *ost
yste.net namespace provide the infomation about IP Address .
)f you pass localhost in <et=ostByName return the IP Address of local machine .
Do$nload Source !ode
Print Source !ode
Imports System.-et
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im 4ostname s IP&ost#ntry , (ns.9et&ostBy-ame('e*tBo*1.'e*t%
(im ip s IPddress(% , 4ostname.ddress1ist
'e*tBo*E.'e*t , ip(;%.'oStrin$(%
#nd Sub
#nd Class
*o( to read a /RL Content
When we want to read content of an 8TM/ page from a remote webserver , in vb.net we are
using DebRe@uest 3 DebResponse . Web2esponse return a treamReader and we can retrieve
the content using a -tream2eader.
Do$nload Source !ode
Print Source !ode
Imports System.-et
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im inStream s Stream6eader
(im )eb6e:uest s +eb6e:uest
(im )ebresponse s +eb6esponse
)eb6e:uest , )eb6e:uest.Create('e*tBo*1.'e*t%
)ebresponse , )eb6e:uest.9et6esponse(%
inStream , -e) Stream6eader()ebresponse.9et6esponseStream(%%
'e*tBo*E.'e*t , inStream.6ead'o#nd(%
#nd Sub
#nd Class
VB.NET Soc)et rogramming
# Soc0et is an End.$oint of To and !rom 0Bidirectional1 communication lin" between two
programs 0-erver $rogram and %lient $rogram 1 running on the networ" . We need two programs
for running a soc"et program. # -erver -oc"et $rogram 0 -erver 1 and a %lient -oc"et $rogram
0 %lient 1 .
Ser"er Proram: # -erver -oc"et $rogram running on a computer has a soc"et that bound to a
Port Number on that computer and listening to the client6s re*uests.
!lient Proram: %lient -oc"et $rogram have to "now the IP Address 0 8ostname 1 of the
computer that the -erver -oc"et $rogram resides and the Port Number assign for listening for
client6s re*uest .
nce the communication is established , the -erver and %lient can read or write their own
soc"ets.
There are two types of communication protocol use for -oc"et $rogramming T!P?IP
0 Transmission %ontrol $rotocol@)nternet protocol 1 %ommunication and =DP?IP 0 3ser
,atagram $rotocol@)nternet protocol 1 %ommunication .
)n the following section we are going to communicate a -erver -oc"et $rogram and %lient
-oc"et $rogram through VB.NET using T!P?IP %ommunication.
)n the above picture shows the communication interfaces .
Ser"er Soc0et Proram:
8ere -erver -oc"et $rogram is done through a %onsole based VB.NET application . 8ere the
-erver listening for the client6s re*uest , and when the server get a re*uest from the %lient ,
-erver sends the response to %lient . %lic" the following lin" to see in detail of a -erver -oc"et
$rogram .
!lient Soc0et Proram:
The %lient -oc"et $rogram is a windows based application . When the client start its get connect
the server and send re*uests , and also receive the response from -erver . %lic" the following
lin" to see in detail of %lient -oc"et $rogram.
4o$ to run t%is proram Q
The -oc"et $rogramming has two sections.
A. -erver -oc"et $rogram
5. %lient -oc"et $rogram
When you finish coding the program , !irst you have to start -erver -oc"et $rogram , then you
will get the ,- screen with a message erver tarted .
Ne+t step is to start %lient -oc"et $rogram . Then you will get message in client screen 6lient
tarted , at the same time you chec" with server screen a message Accept connection $rom
client .
Now your -erver -oc"et $rogram and %lient -oc"et $rogram get connected . )f you want to test
the communication , you clic" the button 0 6lic! here to send data to erver 1 in client window ,
then you can see changes in -erver and %lient screen messages .
VB.NET Client Soc)et rogram
The -oc"et $rogramming has two sections.
A. -erver -oc"et $rogram
5. %lient -oc"et $rogram
The !lient Soc0et Proram is the continuation of the -erver -oc"et $rogram . The !lient
Soc0et Proram is a Windows based application . %lient connect to the Port AAAA of the -erver
-oc"et $rogram , and the IP Address 0%omputer Name1 here we give as .8D.>.>.. , because the
-erver and client running on the same machine .
clientoc!et.6onnect.)'&P.(.(.')3 KKKK/
When client gets connected , it reads data from Net9or!tream , and also write to
Net9or!tream . When you start the client program you will get message client started . When
press the button at the bottom its send a message to -erver and also receive a message from
-erver.
Do$nload Source !ode
Print Source !ode
Imports System.-et.Sockets
Imports System.'e*t
Public Class Form1
(im clientSocket s -e) System.-et.Sockets.'cpClient(%
(im serverStream s -et)orkStream
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im serverStream s -et)orkStream , clientSocket.9etStream(%
(im outStream s Byte(% , _
System.'e*t.#ncodin$.SCII.9etBytes(.5essa$e 3rom ClientQ.%
serverStream.+rite(outStream" ;" outStream.1en$t4%
serverStream.Flus4(%
(im inStream(1;;EG% s Byte
serverStream.6ead(inStream" ;" CInt(clientSocket.6eceiveBu33erSi<e%%
(im returndata s Strin$ , _
System.'e*t.#ncodin$.SCII.9etStrin$(inStream%
ms$(.(ata 3rom Server / . N returndata%
#nd Sub
Private Sub Form1_1oad(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles 5yBase.1oad
ms$(.Client Started.%
clientSocket.Connect(.1EK.;.;.1." JJJJ%
1abel1.'e*t , .Client Socket Pro$ram 2 Server Connected ....
#nd Sub
Sub ms$(ByVal mes$ s Strin$%
'e*tBo*1.'e*t , 'e*tBo*1.'e*t N #nvironment.-e)1ine N . SS . N mes$
#nd Sub
#nd Class
Brfore you run the !lient Soc0et Proram you should start -erver -oc"et $rogram first . !or
more details of running this program , ta"e a loo" at the VB.NET -oc"et $rogramming .
VB.NET 'ultiT#readed Soc)et rogramming
7ultit%readed Soc0et Prorammin means that a Multithreaded -erver can communicate with
more than one clients at the same time . )n the previous section -oc"et $rogramming , the -erver
-oc"et $rogram can communicate with only one client at a time . That means it s not possible to
connect another %lient -oc"et $rogram at the same time to communicate with -erver . !rom the
following figure you can understand how to a -erver can communicate with more than one client
at the same time .?ou can see the basics of -oc"et $rogramming in the previous section , ta"e a
loo" at -oc"et $rogramming before you start this section.
The basic idea behind 7ultit%readed Soc0et Prorammin is, whenever -erver gets a
connection re*uest from %lient , the -erver create a separate 0 independent 1 Thread for the each
%lient re*uest. That means for each %lient, there is a separate %lient Thread in -erver . -o the
%lient can communicate independently with their own %lient Thread in -erver.
)n the following sections you can see in detail of 8ow a 7ultit%readed Soc0et Prorammin
can communicate with more than one client at the same time.
The Multithreaded -oc"et $rogramming has two sections.
A. Multithreaded -erver -oc"et $rogram
5. Multithreaded %lient -oc"et $rogram
4o$ to run t%is proram Q
%reate Multithreaded -erver -oc"et $rogram and Multithreaded %lient -oc"et $rogram and run
the -erver program first . Then you will get message of G-erver startedG . Ne+t you start the
%lient program , then you can see the message from -erver . ?ou can start more than one client
same time and communicate with -erver . !or each client -erver responds with the %lients
%onnection ), Number.
VB.NET 'ultiT#readed Ser0er Soc)et rogramming
7ultiT%readed Ser"er Soc0et Proram here is a VB.NET %onsole based application , that can
handle multiple clients at the same time. ?ou can see the basics of -oc"et $rogramming in the
previous section , ta"e a loo" at -oc"et $rogramming before you start this section.
The Multithreaded -oc"et $rogramming has two sections.
A. Multithreaded -erver -oc"et $rogram
5. Multithreaded %lient -oc"et $rogram
8ere we create a -erver -oc"et from Tcp;istener class and listen to P#(T AAAA . When the
server gets a re*uest from %lient , the -erver pass the instance of the client re*uest to a separate
class handle6lient . )n handle%lient class there is a Thread , handling the communication
between the instance of -erver side client and %lient from outside .
!or each re*uest , in -erver there is a new thread instant is create for communication , so we can
connect more than one client at the same time to -erver and communicate independently .
%reate a new VB.NET %onsole #pplication pro9ect and put the following source code in the
pro9ect.
Do$nload Source !ode
Print Source !ode
Imports System.-et.Sockets
Imports System.'e*t
5odule 5odule1
Sub 5ain(%
(im serverSocket s -e) 'cp1istener(JJJJ%
(im clientSocket s 'cpClient
(im counter s Inte$er
serverSocket.Start(%
ms$(.Server Started.%
counter , ;
+4ile ('rue%
counter N, 1
clientSocket , serverSocket.ccept'cpClient(%
ms$(.Client -o/. N Convert.'oStrin$(counter% N . started7.%
(im client s -e) 4andleClinet
client.startClient(clientSocket" Convert.'oStrin$(counter%%
#nd +4ile
clientSocket.Close(%
serverSocket.Stop(%
ms$(.e*it.%
Console.6ead1ine(%
#nd Sub
Sub ms$(ByVal mes$ s Strin$%
mes$.'rim(%
Console.+rite1ine(. SS . N mes$%
#nd Sub
Public Class 4andleClinet
(im clientSocket s 'cpClient
(im cl-o s Strin$
Public Sub startClient(ByVal inClientSocket s 'cpClient" _
ByVal cline-o s Strin$%
5e.clientSocket , inClientSocket
5e.cl-o , cline-o
(im ct'4read s '4readin$.'4read , -e) '4readin$.'4read(ddressO3 doC4at%
ct'4read.Start(%
#nd Sub
Private Sub doC4at(%
(im re:uestCount s Inte$er
(im bytesFrom(1;;EG% s Byte
(im dataFromClient s Strin$
(im sendBytes s ?Byte@(%
(im server6esponse s Strin$
(im rCount s Strin$
re:uestCount , ;
+4ile ('rue%
'ry
re:uestCount , re:uestCount N 1
(im net)orkStream s -et)orkStream , _
clientSocket.9etStream(%
net)orkStream.6ead(bytesFrom" ;" CInt(clientSocket.6eceiveBu33erSi<e%%
dataFromClient , System.'e*t.#ncodin$.SCII.9etStrin$(bytesFrom%
dataFromClient , _
dataFromClient.Substrin$(;" dataFromClient.Inde*O3(.Q.%%
ms$(.From client2. N cl-o N dataFromClient%
rCount , Convert.'oStrin$(re:uestCount%
server6esponse , .Server to clinet(. N cl-o N .% . N rCount
sendBytes , #ncodin$.SCII.9etBytes(server6esponse%
net)orkStream.+rite(sendBytes" ;" sendBytes.1en$t4%
net)orkStream.Flus4(%
ms$(server6esponse%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd +4ile
#nd Sub
#nd Class
#nd 5odule
The Multithreaded -oc"et $rogramming has two sections.
A. Multithreaded -erver -oc"et $rogram
5. Multithreaded %lient -oc"et $rogram
?ou have to run -erver program first and then %lient program , then only you can communicate
with -erver and %lient each other .
VB.NET 'ultiT#readed Client Soc)et rogramming
The Multithreaded -oc"et $rogramming has two sections.
A. Multithreaded -erver -oc"et $rogram
5. Multithreaded %lient -oc"et $rogram
7ultiT%readed !lient Soc0et Proram is a windows based application . 8ere the client
program is connected to -erver6s P#(T AAAA , and IP Address here we give -erver #ddress as G
.8D.>.>.. G , because -erver and %lient program run on the same machine.
clientoc!et.6onnect.)'&P.(.(.')3 KKKK/
When the %lient get conncted to the -erver , the -erver ma"e a separate thread for %lient6s
communication . -o we can connect more than one client and communicate at the same time.
%reate a new VB.NET Windows based application and put the following source code in the
$ro9ect.
Do$nload Source !ode
Print Source !ode
Imports System.-et.Sockets
Imports System.'e*t
Public Class Form1
(im clientSocket s -e) System.-et.Sockets.'cpClient(%
(im serverStream s -et)orkStream
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im serverStream s -et)orkStream , clientSocket.9etStream(%
(im bu33Si<e s Inte$er
(im outStream s Byte(% , _
System.'e*t.#ncodin$.SCII.9etBytes(.5essa$e 3rom ClientQ.%
serverStream.+rite(outStream" ;" outStream.1en$t4%
serverStream.Flus4(%
(im inStream(1;;EG% s Byte
bu33Si<e , clientSocket.6eceiveBu33erSi<e
serverStream.6ead(inStream" ;" bu33Si<e%
(im returndata s Strin$ , _
System.'e*t.#ncodin$.SCII.9etStrin$(inStream%
ms$(.(ata 3rom Server / . N returndata%
#nd Sub
Private Sub Form1_1oad(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles 5yBase.1oad
ms$(.Client Started.%
clientSocket.Connect(.1EK.;.;.1." JJJJ%
1abel1.'e*t , .Client Socket Pro$ram 2 Server Connected ....
#nd Sub
Sub ms$(ByVal mes$ s Strin$%
'e*tBo*1.'e*t , 'e*tBo*1.'e*t N #nvironment.-e)1ine N . SS . N mes$
#nd Sub
#nd Class
The Multithreaded -oc"et $rogramming has two sections.
A. Multithreaded -erver -oc"et $rogram
5. Multithreaded %lient -oc"et $rogram
?ou have to run -erver program first and then %lient program , then only you can communicate
with -erver and %lient each other .
VB.NET C#at Ser0er rogram
Multithreaded -oc"et $rogramming is the basic idea behind a T%$ %hat -erver communication.
)n the previous section Multithreaded -oc"et $rogramming we can see a Multithreaded -erver
-oc"et $rogram communicate with more than one %lient at the same time . But there the
communication is happening only between -erver to %lient or %lient to -erver , there is no
communication between %lient to %lient . )n a 7ultit%readed !%at Ser"er , a %lient can
communicate with any number of %lients , currently connected on the %hat -erver .
Each %lients send messages to -erver and the -erver broadcast the message to all %lients
currently connected to the %hat -erver . !rom the following diagram you can see how a VB.NET
T!P !%at Ser"er is handling communication between %lient to %lient .
The VB.NET 7ultit%readed !%at Ser"er program has two sections.
A. %hat -erver
5. %hat %lient
Do$nload !%at Ser"er Proram .
%hat -erver ,ownload
%hat %lient ,ownload
8ow to run %hat -erver program V
#fter create the %hat -erver and %hat %lient , run the -erver program first and then run the
%lient program . )n the %lient program Enter a %hat name and clic" the G 6onnect to erver G
button . Then you can see the message in the -erver program 3ser Foined 6hat Room . -imilarly
you can connect more than one %lients at the same time and start chatting each other. )t is better
to %ompile and Build the program and run from the .e+e files .
VB.NET C#at Ser0er
The basic function of the !%at Ser"er here is to listening for the connection re*uest from %lients
and when the -erver get a message , it Broadcast the message to all %lients currently connected
to the -erver .
The VB.NET Multithreaded %hat -erver $rogram has two sections.
A. %hat -erver
5. %hat %lient
The %hat -erver here is a VB.NET %onsole based application and is listening to the P#(T AAAA
for the connection re*uest from clients . When the server gets a connection re*uest , it add the
name of the %lient into a clients)ist 0 8ere it is a 8ashtable 1 and create a new thread for
communication with -erver . When the -erver get a message from any client , it select all the
%lients from clients)ist and send the message to all %lients 0 ie we can say Broadcast 1 in the
clients/ist . -o each %lient can see the message each other and they can communicate through
%hat -erver.
The client list we implemented here in a =ashTable . The clients/ist stores the !lient Name 0 ie
the first message from %lient 1 and an instance of the !lient Soc0et .
When a %hat %lient connected to -erver , the -erver create a new Thread for communication .
8ere we implement a %lass handle6lient for handling %lient as a separate T%read . The %lass
handle6lient has a function do6hat./ is handling the communication between the -erver side
%lient -oc"et and the incoming %lient -oc"et.
When -erver get a message from any of the currently connected %hat %lient , the -erver
Broadcast the message to all %lients. 8ere we implement a function broadcast for sending
messages to all %lients .
%reate a new VB.NET %onsole based application and put the following source code into the
$ro9ect.
Do$nload Source !ode
Print Source !ode
Imports System.-et.Sockets
Imports System.'e*t
5odule 5odule1
(im clients1ist s -e) &as4table
Sub 5ain(%
(im serverSocket s -e) 'cp1istener(JJJJ%
(im clientSocket s 'cpClient
(im counter s Inte$er
serverSocket.Start(%
ms$(.C4at Server Started .....%
counter , ;
+4ile ('rue%
counter N, 1
clientSocket , serverSocket.ccept'cpClient(%
(im bytesFrom(1;;EG% s Byte
(im dataFromClient s Strin$
(im net)orkStream s -et)orkStream , _
clientSocket.9etStream(%
net)orkStream.6ead(bytesFrom" ;" CInt(clientSocket.6eceiveBu33erSi<e%%
dataFromClient , System.'e*t.#ncodin$.SCII.9etStrin$(bytesFrom%
dataFromClient , _
dataFromClient.Substrin$(;" dataFromClient.Inde*O3(.Q.%%
clients1ist(dataFromClient% , clientSocket
broadcast(dataFromClient N . Moined ." dataFromClient" False%
ms$(dataFromClient N . Moined c4at room .%
(im client s -e) 4andleClinet
client.startClient(clientSocket" dataFromClient" clients1ist%
#nd +4ile
clientSocket.Close(%
serverSocket.Stop(%
ms$(.e*it.%
Console.6ead1ine(%
#nd Sub
Sub ms$(ByVal mes$ s Strin$%
mes$.'rim(%
Console.+rite1ine(. SS . N mes$%
#nd Sub
Private Sub broadcast(ByVal ms$ s Strin$" _
ByVal u-ame s Strin$" ByVal 3la$ s Boolean%
(im Item s (ictionary#ntry
For #ac4 Item In clients1ist
(im broadcastSocket s 'cpClient
broadcastSocket , C'ype(Item.Value" 'cpClient%
(im broadcastStream s -et)orkStream , _
broadcastSocket.9etStream(%
(im broadcastBytes s ?Byte@(%
I3 3la$ , 'rue '4en
broadcastBytes , #ncodin$.SCII.9etBytes(u-ame N . says / . N ms$%
#lse
broadcastBytes , #ncodin$.SCII.9etBytes(ms$%
#nd I3
broadcastStream.+rite(broadcastBytes" ;" broadcastBytes.1en$t4%
broadcastStream.Flus4(%
-e*t
#nd Sub
Public Class 4andleClinet
(im clientSocket s 'cpClient
(im cl-o s Strin$
(im clients1ist s &as4table
Public Sub startClient(ByVal inClientSocket s 'cpClient" _
ByVal cline-o s Strin$" ByVal c1ist s &as4table%
5e.clientSocket , inClientSocket
5e.cl-o , cline-o
5e.clients1ist , c1ist
(im ct'4read s '4readin$.'4read , -e) '4readin$.'4read(ddressO3 doC4at%
ct'4read.Start(%
#nd Sub
Private Sub doC4at(%
D(im in3initeCounter s Inte$er
(im re:uestCount s Inte$er
(im bytesFrom(1;;EG% s Byte
(im dataFromClient s Strin$
(im sendBytes s ?Byte@(%
(im server6esponse s Strin$
(im rCount s Strin$
re:uestCount , ;
+4ile ('rue%
'ry
re:uestCount , re:uestCount N 1
(im net)orkStream s -et)orkStream , _
clientSocket.9etStream(%
net)orkStream.6ead(bytesFrom" ;" CInt(clientSocket.6eceiveBu33erSi<e%%
dataFromClient , System.'e*t.#ncodin$.SCII.9etStrin$(bytesFrom%
dataFromClient , _
dataFromClient.Substrin$(;" dataFromClient.Inde*O3(.Q.%%
ms$(.From client 2 . N cl-o N . / . N dataFromClient%
rCount , Convert.'oStrin$(re:uestCount%
broadcast(dataFromClient" cl-o" 'rue%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd +4ile
#nd Sub
#nd Class
#nd 5odule
Do$nload !%at Ser"er Proram .
%hat -erver ,ownload
%hat %lient ,ownload
2efer to %hat -erver $rogram for how to run this program .
VB.NET C#at Client
The !%at !lient is a Windows based #pplication and its main function is to send message to
%hat -erver.
The VB.NET Multithreaded %hat -erver $rogram has two sections.
A. %hat -erver
5. %hat %lient
The !%at !lient here is to connect the P#(T AAAA of the %hat -erver in G .8D.>.>.. G . 8ere we
give G .8D.>.>.. G , because %hat -erver and !%at !lient are running on the same machine .
When we start the !%at !lient program , we have to enter a 3ser Name for identifying in -erver
. The %lient program connect to the %hat -erver and start a T%read for receive the messages
from client, . 8ere we implement an infinite loop in the function get,essage./ and call this
function in a T%read .
%reate a new VB.NET Windows based pro9ect and put the source code in it.
Do$nload Source !ode
Print Source !ode
Imports System.-et.Sockets
Imports System.'e*t
Public Class Form1
(im clientSocket s -e) System.-et.Sockets.'cpClient(%
(im serverStream s -et)orkStream
(im read(ata s Strin$
(im in3initeCounter s Inte$er
Private Sub Button1_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles Button1.Click
(im outStream s Byte(% , _
System.'e*t.#ncodin$.SCII.9etBytes('e*tBo*E.'e*t N .Q.%
serverStream.+rite(outStream" ;" outStream.1en$t4%
serverStream.Flus4(%
#nd Sub
Private Sub ms$(%
I3 5e.Invoke6e:uired '4en
5e.Invoke(-e) 5et4odInvoker(ddressO3 ms$%%
#lse
'e*tBo*1.'e*t , 'e*tBo*1.'e*t N _
#nvironment.-e)1ine N . SS . N read(ata
#nd I3
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" _
ByVal e s System.#ventr$s% &andles ButtonE.Click
read(ata , .Conected to C4at Server ....
ms$(%
clientSocket.Connect(.1EK.;.;.1." JJJJ%
D1abel1.'e*t , .Client Socket Pro$ram 2 Server Connected ....
serverStream , clientSocket.9etStream(%
(im outStream s Byte(% , _
System.'e*t.#ncodin$.SCII.9etBytes('e*tBo*H.'e*t N .Q.%
serverStream.+rite(outStream" ;" outStream.1en$t4%
serverStream.Flus4(%
(im ct'4read s '4readin$.'4read , _
-e) '4readin$.'4read(ddressO3 $et5essa$e%
ct'4read.Start(%
#nd Sub
Private Sub $et5essa$e(%
For in3initeCounter , 1 'o E
in3initeCounter , 1
serverStream , clientSocket.9etStream(%
(im bu33Si<e s Inte$er
(im inStream(1;;EG% s Byte
bu33Si<e , clientSocket.6eceiveBu33erSi<e
serverStream.6ead(inStream" ;" bu33Si<e%
(im returndata s Strin$ , _
System.'e*t.#ncodin$.SCII.9etStrin$(inStream%
read(ata , .. N returndata
ms$(%
-e*t
#nd Sub
#nd Class
Do$nload !%at Ser"er Proram .
%hat -erver ,ownload
%hat %lient ,ownload
2efer to %hat -erver $rogram for how to run this program .
VB.NET Email .ttac#ment
The -ystem.Net classes uses to communicate with other applications by using the 8TT$, T%$,
3,$, -oc"et etc. Microsoft .Net languages uses -ystem.Net.Mail namespace for sending email .
!rom the previous chapters we learned how to send an email with a te+t body. 8ere we are trying
to send an eamil with attachment.
.im attachment /s "0stem.'et.-ail./ttachment
attachment = 'ew "0stem.'et.-ail./ttachment(10our attachment +ile1)
mail./ttachments./dd(attachment)
The following VB.NET source code shows how to send an email with an attachment from a
7mail address . The 7mail -MT$ server name is smtp.gmail.com and the port using send mail is
ICB . 8ere using Networ"%redential for password based authentication.
"mt2"er,er.Port = 345
"mt2"er,er.Credentials = 'ew "0stem.'et.'etworkCredential(1username1$
12assword1)
"mt2"er,er.6nable"sl = True
Do$nload Source !ode
Print Source !ode
Imports System.-et.5ail
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal
e s System.#ventr$s% &andles Button1.Click
(im mail s -e) 5ail5essa$e(%
(im SmtpServer s -e) SmtpClient(.smtp.$mail.com.%
mail.From , -e)
5ailddress(.your_email_addressT$mail.com.%
mail.?'o@.dd(.to_address.%
mail.Sub!ect , .'est 5ail 2 1.
mail.Body , .mail )it4 attac4ment.
(im attac4ment s System.-et.5ail.ttac4ment
attac4ment , -e) System.-et.5ail.ttac4ment(.your
attac4ment 3ile.%
mail.ttac4ments.dd(attac4ment%
SmtpServer.Port , IJK
SmtpServer.Credentials , -e)
System.-et.-et)orkCredential(.username." .pass)ord.%
SmtpServer.#nableSsl , 'rue
SmtpServer.Send(mail%
5essa$eBo*.S4o)(.mail Send.%
#nd Sub
#nd Class
.D+.NET .rc#itecture
#,.NET is a data access technology from Microsoft .Net !ramewor" , which provides
communication between relational and non.relational systems through a common set of
components . #,.NET consist of a set of b9ects that e+pose data access services to the .NET
environment. #,.NET is built for disconnected architecture , so it enables truly disconnected
,ata #ccess and ,ata Manipulation through its ,ataset b9ect, which is completely independent
from the ,ata -ource.
The two "ey components of #,.NET are ,ata $roviders and ,ata-et . The .Net !ramewor"
includes mainly three ,ata $roviders for #,.NET. They are the Microsoft -P/ -erver ,ata
$rovider, /E,B ,ata $rovider and ,B% ,ata $rovider. -P/ -erver uses the -*l%onnection
ob9ect , /E,B uses the le,b%onnection b9ect and ,B% uses dbc%onnection b9ect
respectively.
The four b9ects from the .Net !ramewor" provide the functionality of ,ata $roviders in the
#,.NET. They are %onnection b9ect, %ommand b9ect , ,ata2eader b9ect and
,ata#dapter b9ect. The %onnection b9ect provides physical connection to the ,ata -ource.
The %ommand b9ect uses to perform -P/ statement or stored procedure to be e+ecuted at the
,ata -ource. The ,ata2eader b9ect is a stream.based , forward.only, read.only retrieval of
*uery results from the ,ata -ource, which do not update the data. !inally the ,ata#dapter
b9ect , which populate a ,ataset b9ect with results from a ,ata -ource .
,ata-et provides a disconnected representation of result sets from the ,ata -ource, and it is
completely independent from the ,ata -ource. ,ata-et provides much greater fle+ibility when
dealing with related 2esult -ets. ,ata-et consists of a collection of ,ataTable ob9ects that you
can relate to each other with ,ata2elation ob9ects. The ,ataTable contains a collection of
,ata2ow and ,ata%oulumn b9ect which contains ,ata. The ,ata#dapter b9ect provides a
bridge between the ,ata-et and the ,ata -ource.
)n the following section you can see each of the #,.NET components in details with vb.net
source code.
.d0antages o! .D+.Net o0er .D+
#, stands for #ctive> ,ata b9ects and it relies on %M whereas #,.NET relies on
managed providers defined by the .NET %/2 0%ommon /anguage 2untime1. #,.NET
provides consistent access to data sources such as -P/ -erver, as well as data sources e+posed
through /E ,B and >M/. While there are similarities between #, and #,.NET, the way
they operate and their foundations are *uite different. The following are some #dvantages of
#,.Net over #, in basic level.
# ma9or difference in creating connections with #, and #,.NET is that #, fits all
connections to all types of data sources into a single %onnection ob9ect. #,.NET can have
separate b9ects that represent connections to different data sources. )n #,.NET you can
create multiple data provider namespaces to connect specifically with a particular data source,
ma"ing access faster and more efficient and allowing each namespace to e+ploit the features of
its targeted data provider.
.im connection /s "7lConnection
connection = 'ew "7lConnection(1connetion"trin81)
.im connection /s 9le.bConnection
connection = 'ew 9le.bConnection(1connetion"trin81)
#, allows you to create client side cursors only whereas #,.NET gives you the choice of
either using client side or server side cursors.
#,.NET introduces a new way of getting a single value from a *uery6s results when you
e+pect only one row and one column to return. The #,.NET command ob9ect has an
E+ecute-calar method which returns the first row and column6s value from its associated *uery.
#,.Net dataset represents in memory representation of a database. #, recordsets is merely a
set of rows retrieved from a data source.
#, recordsets can hold data from one data source at a time. #,.Net datasets can hold data
from various sources and integrate the data and write it bac" to one or several data sources.
The #,.NET !ramewor" supports two models of ,ata #ccess #rchitecture, %onnection
riented ,ata #ccess #rchitecture and ,isconnected ,ata #ccess #rchitecture.
)n the case of ,ata %ommunication , #, ob9ects communicate in binary mode while
#,.NET uses >M/ for passing the data.
?ou can find more information on #, to #,.NET from the following lin" =
http=@@msdn.microsoft.com@en.us@maga:ine@ccA;4JI<.asp+
Connected and Disconnected Data .ccess
.rc#itecture
The #,.NET !ramewor" supports two models of ,ata #ccess #rchitecture, %onnection
riented ,ata #ccess #rchitecture and ,isconnected ,ata #ccess #rchitecture.
)n %onnection riented ,ata #ccess #rchitecture the application ma"es a connection to the ,ata
-ource and then interact with it through -P/ re*uests using the same connection. )n these cases
the application stays connected to the database system even when it is not using any ,atabase
perations.
#,.Net solves this problem by introduces a new component called ,ataset. The ,ata-et is the
central component in the #,.NET ,isconnected ,ata #ccess #rchitecture. # ,ata-et is an in.
memory data store that can hold multiple tables at the same time. ,ata-ets only hold data and do
not interact with a ,ata -ource. ne of the "ey characteristics of the ,ata-et is that it has no
"nowledge of the underlying ,ata -ource that might have been used to populate it.
.im ds /s 'ew .ata"et
)n %onnection riented ,ata #ccess, when you read data from a database by using a ,ata2eader
ob9ect, an open connection must be maintained between your application and the ,ata -ource.
3nli"e the ,ata2eader, the ,ata-et is not connected directly to a ,ata -ource through a
%onnection ob9ect when you populate it. )t is the ,ata#dapter that manages connections between
,ata -ource and ,ataset by fill the data from ,ata -ource to the ,ataset and giving a
disconnected behavior to the ,ataset. The ,ata#dapter acts as a bridge between the %onnected
and ,isconnected b9ects.
.im ada2ter /s 'ew "7l.ata/da2ter(1s7l1$ 1connection1)
.im ds /s 'ew .ata"et
ada2ter.Fill(ds$ 1"rc Table1)
By "eeping connections open for only a minimum period of time, #, .NET conserves system
resources and provides ma+imum security for databases and also has less impact on system
performance.
.D+.NET ConnectionString
%onnection -tring is a normal -tring representation which contains ,atabase connection
information to establish the connection between ,atbase and the #pplication. The %onnection
-tring includes parameters such as the name of the driver, -erver name and ,atabase name , as
well as security information such as user name and password. ,ata providers use a connection
string containing a collection of parameters to establish the connection with the database.
The .NET !ramewor" provides mainly three data providers= Microsoft -P/ -erver, /E,B and
,B%. 8ere you can see how to ma"e connection string to these #,.NET ,ata $roviders.
7icroso't SR) Ser"er !onnection Strin
connetiontring #)Data ource # erverNameI Initial 6atalog # DatabasenameI Lser ID #
LserNameI 2ass9ord#2ass9ord)
#)EDB Data Pro"ider !onnection Strin
connetiontring # )2rovider # ,icroso$t.Fet.5;EDB.+.(I Data ource #
yourdatabasename.mdbI)
#DB! !onnection Strin
connetiontring # )Driver # B,icroso$t Access Driver .G.mdb/CI DBA #
yourdatabasename.mdbI)
Note = ?ou have to provide the necessary informations to the %onnection -tring attributes.
)n the following section you can see how to these #,.NET ,ata $roviders establish connection
to the ,atabse in detail.
-P/ -erver %onnection
/E,B %onnection
,B% %onnection
.D+.NET Data ro0iders
The .Net !ramewor" includes mainly three ,ata $roviders for #,.NET. They are the
Microsoft -P/ -erver ,ata $rovider , /E,B ,ata $rovider and ,B% ,ata provider. ?ou can
see from the following lin"s how these ,ata $roviders ma"ing connection to the specified data
-ources.
-P/ -erver %onnection
/E,B %onnection
,B% %onnection
The four b9ects from the .Net !ramewor" provide the functionality of ,ata $roviders in
#,.NET. They are %onnection b9ect, %ommand b9ect , ,ata2eader b9ect and
,ata#dapter b9ect. The following lin" shows in details about these b9ects.
%onnection
%ommand
,ata2eader
,ata#dapter
.D+.NET Connection +$1ect
The %onnection b9ect is a part of #,.NET ,ata $rovider and it is a uni*ue session with the
,ata -ource. )n .Net !ramewor" the %onnection b9ect is 8andling the part of physical
communication between the application and the ,ata -ource. ,epends on the parameter
specified in the %onnection -tring , #,.NET %onnection b9ect connect to the specified
,atabase and open a connection between the application and the ,atabase . When the connection
is established , -P/ %ommands may be e+ecuted, with the help of the %onnection b9ect, to
retrieve or manipulate data in the ,atabase. nce the ,atabase activity is over , %onnection
should be closed and release the resources .
)n #,.NET the type of the %onnection is depend on what ,atabase system you are wor"ing
with. The following are the commonly using the connections in the #,.NET
-*l%onnection
le,b%onnection
dbc%onnection
.D+.NET S%L Ser0er Connection
The -*l%onnection b9ect is 8andling the part of physical communication between the
application and the -P/ -erver ,atabase. #n instance of the -*l%onnection class in .NET
!ramewor" is supported the ,ata $rovider for -P/ -erver ,atabase. The -*l%onnection
instance ta"es %onnection -tring as argument and pass the value to the %onstructor statement.
When the connection is established , -P/ %ommands may be e+ecuted, with the help of the
%onnection b9ect, to retrieve or manipulate data in the database. nce the ,atabase activities
over , %onnection should be closed and release the database resources .
The %lose01 method in -*l%onnection class is used to close the ,atabase %onnection. The %lose
method rolls bac" any pending transactions and releases the %onnection from the -P/ -erver
,atabase.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s S:lConnection
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
cnn , -e) S:lConnection(connetionStrin$%
'ry
cnn.Open(%
5s$Bo*(.Connection Open 7 .%
cnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
?ou have to provide the necessary informations to the %onnection -tring.
connetiontring # )Data ource # erverNameI Initial 6atalog # DatabaseNameI Lser ID #
LserNameI 2ass9ord # 2ass9ord)
!rom the above statement replace -erverName, ,atabaseName, 3serName, $assword to the
actual names.
.D+.NET +LEDB Connection
#n instance of the le,b%onnection class in .NET !ramewor" is supported the /E,B ,ata
$rovider. The le,b%onnection instance ta"es %onnection -tring as argument and pass the value
to the %onstructor statement. When the connection is established , -P/ %ommands may be
e+ecuted, with the help of the %onnection b9ect, to retrieve or manipulate data in the database.
nce the ,atabase activities over , %onnection should be closed and release the resources . The
%lose01 method in -*l%onnection class is used to close the ,atabase %onnection. The %lose
method rolls bac" any pending transactions and releases the %onnection from the ,atabase
connected by the /E,B ,ata $rovider.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s Ole(bConnection
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata
Source,yourdatabasename.mdbO.
cnn , -e) Ole(bConnection(connetionStrin$%
'ry
cnn.Open(%
5s$Bo*(.Connection Open 7 .%
cnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
?ou have to provide the necessary informations to the %onnection -tring.
connetiontring # )2rovider # ,icroso$t.Fet.5;EDB.+.(I Data ource #
yourdatabasename.mdbI)
!rom the above statement replace yourdatabasename.mdb to the actual names.
.D+.NET +DBC Connection
#n instance of the dbc%onnection class in .NET !ramewor" is supported the ,B% ,ata
$rovider. The dbc%onnection instance ta"es %onnection -tring as argument and pass the value
to the %onstructor statement. When the connection is established , -P/ %ommands may be
e+ecuted, with the help of the %onnection b9ect, to retrieve or manipulate data in the database.
nce the ,atabase activities over , %onnection should be closed and release the resources . The
%lose01 method in -*l%onnection class is used to close the ,atabase %onnection. The %lose
method rolls bac" any pending transactions and releases the %onnection from the ,atabase
connected by the ,B% ,ata $rovider.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Odbc
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s OdbcConnection
connetionStrin$ , .(river,U5icroso3t ccess (river
(P.mdb%VO(BC,yourdatabasename.mdbO.
cnn , -e) OdbcConnection(connetionStrin$%
'ry
cnn.Open(%
5s$Bo*(.Connection Open 7 .%
cnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
?ou have to provide the necessary informations to the %onnection -tring.
connetiontring # )Driver # B,icroso$t Access Driver .G.mdb/CI DBA #
yourdatabasename.mdbI)
!rom the above statement replace yourdatabasename.mdb to the actual names.
.D+.NET Command
The %ommand b9ect in #,.NET e+ecutes -P/ statements and -tored $rocedures against the
data source specified in the %onnection b9ect. The %ommand b9ect re*uired an instance of a
%onnection b9ect for e+ecuting the -P/ statements. That is, for retrieving data or e+ecute an
-P/ statement against a ,ata -ource , you have to create a %onnection b9ect and open a
connection to the ,ata -ource, and assign the open connection to the connection property of the
%ommand b9ect. When the %ommand b9ect return result set , a ,ata 2eader is used to retrieve
the result set.
The %ommand b9ect has a property called %ommandTe+t, which contains a -tring value that
represents the command that will be e+ecuted in the ,ata -ource. When the %ommandType
property is set to -tored$rocedure, the %ommandTe+t property should be set to the name of the
stored procedure.
%lic" the following lin"s to see some important built in methods uses in the %ommand b9ect to
e+ecute the -P/ statements.
E+ecuteNonPuery
E+ecute2eader
E+ecute-calar
.D+.NET ExecuteNon%uery in S2lCommand +$1ect
E+ecuteNonPuery01 is one of the most fre*uently used method in -*l%ommand b9ect and is
used for e+ecuting statements that do not return result set. E+ecuteNonPuery01 performs ,ata
,efinition tas"s as well as ,ata Manipulation tas"s also. The ,ata ,efinition tas"s li"e creating
-tored $rocedures and Views perform by E+ecuteNonPuery01 . #lso ,ata Manipulation tas"s
li"e )nsert , 3pdate and ,elete perform by E+ecuteNonPuery01.
The following e+ample shows how to use the method E+ecuteNonPuery01 through -*l%ommand
b9ect.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s S:lConnection
(im cmd s S:lCommand
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Rour SC1 Statement &ere.
cnn , -e) S:lConnection(connetionStrin$%
'ry
cnn.Open(%
cmd , -e) S:lCommand(S:l" cnn%
cmd.#*ecute-onCuery(%
cmd.(ispose(%
cnn.Close(%
5s$Bo*(. #*ecute-onCuery in S:lCommand e*ecuted 77.%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource # erverNameI Initial 6atalog # DatabaseNameI Lser ID #
LserNameI 2ass9ord # 2ass9ord)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your realtime variables.
.D+.NET ExecuteNon%uery in +leD$Command
+$1ect
E+ecuteNonPuery01 is one of the most fre*uently used method in le,b%ommand b9ect and is
used for e+ecuting statements that do not return result set. E+ecuteNonPuery01 performs ,ata
,efinition tas"s as well as ,ata Manipulation tas"s also. The ,ata ,efinition tas"s li"e creating
-tored $rocedures and Views perform by E+ecuteNonPuery01 . #lso ,ata Manipulation tas"s
li"e )nsert , 3pdate and ,elete perform by E+ecuteNonPuery01.
The following e+ample shows how to use the method E+ecuteNonPuery01 through
le,b%ommand b9ect.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s Ole(bConnection
(im cmd s Ole(bCommand
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere.
cnn , -e) Ole(bConnection(connetionStrin$%
'ry
cnn.Open(%
cmd , -e) Ole(bCommand(s:l" cnn%
cmd.#*ecute-onCuery(%
cmd.(ispose(%
cnn.Close(%
5s$Bo*(. #*ecute-onCuery in Ole(bConnection e*ecuted 77.%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider # ,icroso$t.Fet.5;EDB.+.(I Data ource # Jour mdb
$ilenameI)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your realtime variables.
.D+.NET ExecuteScalar in S2lCommand +$1ect
E+ecute-calar01 in -*l%ommand b9ect is used for get a single value from ,atabase after its
e+ecution. )t e+ecutes -P/ statements or -tored $rocedure and returned a scalar value on first
column of first row in the 2esult -et. )f the 2esult -et contains more than one columns or rows ,
it ta"es only the first column of first row, all other values will ignore. )f the 2esult -et is empty it
will return a Null reference.
)t is very useful to use with aggregate functions li"e %ount0N1 or -um01 etc. When compare to
E+ecute2eader01 , E+ecute-calar01 uses fewer -ystem resources.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s S:lConnection
(im cmd s S:lCommand
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Rour SC1 Statement &ere like Select Count(P% 3rom product.
cnn , -e) S:lConnection(connetionStrin$%
'ry
cnn.Open(%
cmd , -e) S:lCommand(s:l" cnn%
(im count s IntHE , Convert.'oIntHE(cmd.#*ecuteScalar(%%
cmd.(ispose(%
cnn.Close(%
5s$Bo*(. -o. o3 6o)s . A count%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource # erverNameI Initial 6atalog # DatabaseNameI Lser ID #
LserNameI 2ass9ord # 2ass9ord)
s@l # )Jour A; tatement =ere li!e elect 6ount.G/ $rom product)
?ou have to replace the string with your realtime variables.
.D+.NET ExecuteScalar in +leD$Command +$1ect
E+ecute-calar01 in le,b%ommand b9ect is used for get a single value from ,atabase after its
e+ecution. )t e+ecutes -P/ statements or -tored $rocedure and returned a scalar value on first
column of first row in the 2esult -et. )f the 2esult -et contains more than one columns or rows ,
it ta"es only the first column of first row, all other values will ignore. )f the 2esult -et is empty it
will return a Null reference. )t is very useful to use with aggregate functions li"e %ount0N1 or
-um01 etc. When compare to E+ecute2eader01 , E+ecute-calar01 uses fewer -ystem resources.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s Ole(bConnection
(im cmd s Ole(bCommand
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere like Select Count(P% 3rom product.
cnn , -e) Ole(bConnection(connetionStrin$%
'ry
cnn.Open(%
cmd , -e) Ole(bCommand(s:l" cnn%
(im count s IntHE , Convert.'oIntHE(cmd.#*ecuteScalar(%%
cmd.(ispose(%
cnn.Close(%
5s$Bo*(. -o o3 6o)s . A count%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider # ,icroso$t.Fet.5;EDB.+.(I Data ource # Jour mdb
$ilenameI)
s@l # )Jour A; tatement =ere li!e elect 6ount.G/ $rom product)
?ou have to replace the string with your realtime variables.
.D+.NET ExecuteReader in S2lCommand +$1ect
E+ecute2eader01 in -*l%ommand b9ect send the -P/ statements to %onnection b9ect and
populate a -*l,ata2eader b9ect based on the -P/ statement. When the E+ecute2eader method
in -*l%ommand b9ect e+ecute , it instantiate a -*l%lient.-*l,ata2eader b9ect.
The -*l,ata2eader b9ect is a stream.based , forward.only, read.only retrieval of *uery results
from the ,ata -ource, which do not update the data. The -*l,ata2eader cannot be created
directly from code, they created only by calling the E+ecute2eader method of a %ommand
b9ect.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s S:lConnection
(im cmd s S:lCommand
(im s:l s Strin$
(im reader s S:l(ata6eader
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Rour SC1 Statement &ere " like Select P 3rom product.
cnn , -e) S:lConnection(connetionStrin$%
'ry
cnn.Open(%
cmd , -e) S:lCommand(s:l" cnn%
reader , cmd.#*ecute6eader(%
+4ile reader.6ead(%
5s$Bo*(reader.Item(;% A . 2 . A reader.Item(1% A . 2 . A
reader.Item(E%%
#nd +4ile
reader.Close(%
cmd.(ispose(%
cnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource # erverNameI Initial 6atalog # DatabaseNameI Lser ID #
LserNameI 2ass9ord # 2ass9ord)
s@l # )Jour A; tatement =ere 3 li!e elect G $rom product)
?ou have to replace the string with your realtime variables.
.D+.NET ExecuteReader in +leD$Command +$1ect
E+ecute2eader01 in le,b%ommand b9ect send the -P/ statements to %onnection b9ect and
populate a le,b,ata2eader b9ect based on the -P/ statement. When the E+ecute2eader
method in le,b%ommand b9ect e+ecute , it instantiate a le,b.le,b,ata2eader b9ect.
The le,b,ata2eader b9ect is a stream.based , forward.only, read.only retrieval of *uery
results from the ,ata -ource, which do not update the data. The le,b,ata2eader cannot be
created directly from code, they created only by calling the E+ecute2eader method of a
%ommand b9ect.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im cnn s Ole(bConnection
(im cmd s Ole(bCommand
(im s:l s Strin$
(im reader s Ole(b(ata6eader
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere like Select P 3rom product.
cnn , -e) Ole(bConnection(connetionStrin$%
'ry
cnn.Open(%
cmd , -e) Ole(bCommand(s:l" cnn%
reader , cmd.#*ecute6eader(%
+4ile reader.6ead(%
5s$Bo*(reader.Item(;% A . 2 . A reader.Item(1% A . 2 . A
reader.Item(E%%
#nd +4ile
reader.Close(%
cmd.(ispose(%
cnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider # ,icroso$t.Fet.5;EDB.+.(I Data ource # Jour mdb
$ilenameI)
s@l # )Jour A; tatement =ere li!e elect G $rom product)
?ou have to replace the string with your realtime variables.
*o( to .D+.NET DataReader
,ata2eader b9ect in #,.NET is a stream.based , forward.only, read.only retrieval of *uery
results from the ,ata -ource, which do not update the data. The ,ata2eader cannot be created
directly from code, they created only by calling the E+ecute2eader method of a %ommand
b9ect.
DataReader # 6ommand.E-ecuteReader./
,ata2eader b9ect provides a connection oriented data access to the data -ources. # %onnection
b9ect can contain only one ,ata2eader at a time and the connection in the ,ata2eader remains
open and cannot be used for any other purpose while data is being accessed. When started to read
from a ,ata2eader it should always be open and positioned prior to the first record. The 2ead01
method in the ,ata2eader is used to read the rows from ,ata2eader and it always moves
forward to a new valid row, if any row e+ist .
DataReader.Raed./
There are two types of ,ata2eader in #,.NET. They are -*l,ata2eader and the
le,b,ata2eader. The -ystem.,ata.-*l%lient and -ystem.,ata.le,b are containing these
,ata2eaders respectively. !rom the following lin" you can see in details about these classes.
-*l,ata2eader
le,b,ata2eader
*o( to .D+.NET S2lDataReader
-*l,ata2eader b9ect provides a connection oriented data access to the -P/ -erver data
-ources. E+ecute2eader01 in the -*l%ommand b9ect send the -P/ statements to -*l%onnection
b9ect and populate a -*l,ata2eader b9ect based on the -P/ statement.
Dim s@lReader As @lDataReader # s@l6md.E-ecuteReader./
When the E+ecute2eader method in -*l%ommand b9ect e+ecute , it instantiate a
-*l%lient.-*l,ata2eader b9ect. When started to read from a ,ata2eader it should always be
open and positioned prior to the first record. The 2ead01 method in the ,ata2eader is used to
read the rows from ,ata2eader and it always moves forward to a new valid row, if any row
e+ist .
@lDataReader.Read./
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im s:lCnn s S:lConnection
(im s:lCmd s S:lCommand
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Rour SC1 Statement &ere " like Select P 3rom product.
s:lCnn , -e) S:lConnection(connetionStrin$%
'ry
s:lCnn.Open(%
s:lCmd , -e) S:lCommand(s:l" s:lCnn%
(im s:l6eader s S:l(ata6eader , s:lCmd.#*ecute6eader(%
+4ile s:l6eader.6ead(%
5s$Bo*(s:l6eader.Item(;% A . 2 . A s:l6eader.Item(1% A . 2
. A s:l6eader.Item(E%%
#nd +4ile
s:l6eader.Close(%
s:lCmd.(ispose(%
s:lCnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )Jour A; tatement =ere 3 li!e elect G $rom product)
?ou have to replace the string with your realtime variables.
*o( to .D+.NET +leD$DataReader
le,b,ata2eader b9ect provides a connection oriented data access to the /E,B ,ata
-ources. E+ecute2eader01 in the le,b%ommand b9ect send the -P/ statements to
le,b%onnection b9ect and populate an le,b,ata2eader b9ect based on the -P/
statement.
Dim oledbReader As 5leDbDataReader # oledb6md.E-ecuteReader./
When the E+ecute2eader method in le,b%ommand b9ect e+ecute , it instantiate an
le,b.le,b,ata2eader b9ect. When started to read from an le,b,ata2eader it should
always be open and positioned prior to the first record. The 2ead01 method in the
le,b,ata2eader is used to read the rows from le,b,ata2eader and it always moves forward
to a new valid row, if any row e+ist .
5leDbDataReader.Read./
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im oledbCnn s Ole(bConnection
(im oledbCmd s Ole(bCommand
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere like Select P 3rom product.
oledbCnn , -e) Ole(bConnection(connetionStrin$%
'ry
oledbCnn.Open(%
oledbCmd , -e) Ole(bCommand(s:l" oledbCnn%
(im oledb6eader s Ole(b(ata6eader , oledbCmd.#*ecute6eader(%
+4ile oledb6eader.6ead
5s$Bo*(oledb6eader.Item(;% A . 2 . A oledb6eader.Item(1% A .
2 . A oledb6eader.Item(E%%
#nd +4ile
oledb6eader.Close(%
oledbCmd.(ispose(%
oledbCnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
s@l # )Jour A; tatement =ere li!e elect G $rom product)
?ou have to replace the string with your realtime variables.
*o( to 'ultiple Result Sets in .D+.NET
The ,ata2eader b9ect is a stream.based , forward.only, read.only retrieval of *uery results
from the ,ata -ource, which do not update the data. When the E+ecute2eader method in
-*l%ommand b9ect e+ecute , it instantiate a -*l%lient.-*l,ata2eader b9ect.
Dim s@lReader As @lDataReader # s@l6md.E-ecuteReader./
)n some situations we need to pass multiple -P/ statements to the %ommand b9ect. )n this
situations the -*l,ata2eader returns multiple 2esult-ets also. !or retrieveing multiple
2esult-ets from -*l,ata2eader we use the Ne+t2esult01 method of the -*l,ata2eader.
@lDataReader.Ne-tResult./
)n the following source code demonstrating how to get multiple result sets from -*l,ata2eader01
.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im s:lCnn s S:lConnection
(im s:lCmd s S:lCommand
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select top E P 3rom productO select top E P 3rom ordermasterO
select top E P 3rom orderdetails.
s:lCnn , -e) S:lConnection(connetionStrin$%
'ry
s:lCnn.Open(%
s:lCmd , -e) S:lCommand(s:l" s:lCnn%
(im s:l6eader s S:l(ata6eader , s:lCmd.#*ecute6eader(%
+4ile s:l6eader.6ead(%
5s$Bo*(.From 3irst SC1 2 . A s:l6eader.Item(;% A . 2 . A
s:l6eader.Item(1%%
#nd +4ile
s:l6eader.-e*t6esult(%
+4ile s:l6eader.6ead(%
5s$Bo*(.From second SC1 2 . A s:l6eader.Item(;% A . 2 . A
s:l6eader.Item(1%%
#nd +4ile
s:l6eader.-e*t6esult(%
+4ile s:l6eader.6ead(%
5s$Bo*(.From t4ird SC1 2 . A s:l6eader.Item(;% A . 2 . A
s:l6eader.Item(1%%
#nd +4ile
s:l6eader.Close(%
s:lCmd.(ispose(%
s:lCnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )elect top & G $rom productI select top & G $rom ordermasterI select top & G $rom
orderdetails)
?ou have to replace the string with your realtime variables.
Sc#ema In!ormations !rom S2lDataReader
The -*l,ata2eader b9ect is a stream.based , forward.only, read.only retrieval of *uery results
from the ,ata -ource, which do not update the data. When the E+ecute2eader method in
-*l%ommand b9ect e+ecute , it instantiate a -*l%lient.-*l,ata2eader b9ect.
DDim s@lReader As @lDataReader # s@l6md.E-ecuteReader./
While a -*l,ata2eader is open, you can retrieve schema information about the current result set
using the 7et-chemaTable method. 7et-chemaTable returns a ,ataTable ob9ect populated with
rows and columns that contain the schema information for the current result set.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im s:lCnn s S:lConnection
(im s:lCmd s S:lCommand
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
s:lCnn , -e) S:lConnection(connetionStrin$%
'ry
s:lCnn.Open(%
s:lCmd , -e) S:lCommand(s:l" s:lCnn%
(im s:l6eader s S:l(ata6eader , s:lCmd.#*ecute6eader(%
(im sc4ema'able s (ata'able , s:l6eader.9etSc4ema'able(%
(im ro) s (ata6o)
(im column s (ataColumn
For #ac4 ro) In sc4ema'able.6o)s
For #ac4 column In sc4ema'able.Columns
5s$Bo*(Strin$.Format(.U;V , U1V." column.Column-ame"
ro)(column%%%
-e*t
-e*t
s:l6eader.Close(%
s:lCmd.(ispose(%
s:lCnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )elect G $rom product)
?ou have to replace the string with your realtime variables.
Sc#ema In!ormations !rom +leD$DataReader
The le,b,ata2eader b9ect is a stream.based , forward.only, read.only retrieval of *uery
results from the ,ata -ource, which do not update the data. When the E+ecute2eader method in
oledb%md b9ect e+ecute , it instantiate a le,b.le,b,ata2eader b9ect.
Dim oledbReader As 5leDbDataReader # oledb6md.E-ecuteReader./
While a le,b,ata2eader is open, you can retrieve schema information about the current result
set using the 7et-chemaTable method. 7et-chemaTable returns a ,ataTable ob9ect populated
with rows and columns that contain the schema information for the current result set.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im oledbCnn s Ole(bConnection
(im oledbCmd s Ole(bCommand
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere like Select P 3rom product.
oledbCnn , -e) Ole(bConnection(connetionStrin$%
'ry
oledbCnn.Open(%
oledbCmd , -e) Ole(bCommand(s:l" oledbCnn%
(im oledb6eader s Ole(b(ata6eader , oledbCmd.#*ecute6eader(%
(im sc4ema'able s (ata'able , oledb6eader.9etSc4ema'able(%
(im ro) s (ata6o)
(im column s (ataColumn
For #ac4 ro) In sc4ema'able.6o)s
For #ac4 column In sc4ema'able.Columns
5s$Bo*(Strin$.Format(.U;V , U1V." column.Column-ame"
ro)(column%%%
-e*t
-e*t
oledb6eader.Close(%
oledbCmd.(ispose(%
oledbCnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
s@l # )Jour A; tatement =ere li!e elect G $rom product)
?ou have to replace the string with your realtime variables.
"#at is Data.dapter
,ata#dapter is a part of the #,.NET ,ata $rovider. ,ata#dapter provides the communication
between the ,ataset and the ,atasource. We can use the ,ata#dapter in combination with the
,ata-et b9ect. That is these two ob9ects combine to enable both data access and data
manipulation capabilities.
The ,ata#dapter can perform -elect , )nsert , 3pdate and ,elete -P/ operations in the ,ata
-ource. The )nsert , 3pdate and ,elete -P/ operations , we are using the continuation of the
-elect command perform by the ,ata#dapter. That is the ,ata#dapter uses the -elect statements
to fill a ,ata-et and use the other three -P/ commands 0)nsert, 3pdate, delete1 to transmit
changes bac" to the ,atabase. !rom the following lin"s describe how to use -*l,ata#dapter and
le,b,ata#dapter in detail.
-*l,ata#dapter
le,b,ata#dapter
"#at is S2lData.dapter
-*l,ata#dapter is a part of the #,.NET ,ata $rovider and it resides in the
-ystem.,ata.-*l%lient namespace. -*l,ata#dapter provides the communication between the
,ataset and the -P/ database. We can use -*l,ata#dapter b9ect in combination with ,ataset
b9ect.
Dim adapter As Ne9 @lDataAdapter
The -*l,ata#dapter b9ect and ,ata-et ob9ects are combine to perform both data access and
data manipulation operations in the -P/ -erver ,atabase. When the user perform the -P/
operations li"e -elect , )nsert etc. in the data containing in the ,ataset b9ect , it won6t directly
affect the ,atabase, until the user invo"e the 3pdate method in the -*l,ata#dapter.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im s:lCnn s S:lConnection
(im s:lCmd s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im i s Inte$er
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-amePass)ord,Pass)ord.
s:l , .Select P 3rom product.
s:lCnn , -e) S:lConnection(connetionStrin$%
'ry
s:lCnn.Open(%
s:lCmd , -e) S:lCommand(s:l" s:lCnn%
adapter.SelectCommand , s:lCmd
adapter.Fill(ds%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
adapter.(ispose(%
s:lCmd.(ispose(%
s:lCnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )elect G $rom product)
?ou have to replace the string with your realtime variables.
"#at is +leD$Data.dapter
le,b,ata#dapter is a part of the #,.NET ,ata $rovider and it resides in the
-ystem.,ata.le,b namespace. le,b,ata#dapter provides the communication between the
,ataset and the le,b ,ata -ources. We can use le,b,ata#dapter b9ect in combination with
,ataset b9ect.
The le,b,ata#dapter b9ect and ,ata-et ob9ects are combine to perform both ,ata #ccess
and ,ata Manipulation operations in the le,b ,ata -ources. When the user perform the -P/
operations li"e -elect , )nsert etc. in the data containing in the ,ataset b9ect , it won6t directly
affect the ,atabase, until the user invo"e the 3pdate method in the le,b,ata#dapter.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im oledbCnn s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im ds s -e) (ataSet
(im s:l s Strin$
(im i s Inte$er
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere like Select P 3rom product.
oledbCnn , -e) Ole(bConnection(connetionStrin$%
'ry
oledbCnn.Open(%
oledbdapter , -e) Ole(b(atadapter(s:l" oledbCnn%
oledbdapter.Fill(ds%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
oledbdapter.(ispose(%
oledbCnn.Close(%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
s@l # )Jour A; tatement =ere li!e elect G $rom product)
?ou have to replace the string with your realtime variables.
V$.NET ExecuteReader and ExecuteNon%uery
Execute(eader : E+ecute2eader used for getting the *uery results as a ,ata2eader ob9ect. )t is
readonly forward only retrieval of records and it uses select command to read through the table
from the first to the last.
.im reader /s "7l.ataReader
reader = Command.6ecuteReader()
!hile reader.Read()
-s8:o(reader.&tem(0))
6nd !hile
reader.Close()
ExecuteNonRuery : E+ecuteNonPuery used for e+ecuting *ueries that does not return any data.
)t is used to e+ecute the s*l statements li"e update, insert, delete etc. E+ecuteNonPuery e+ecutes
the command and returns the number of rows affected.
.im ret;alue /s &nte8er
Command = 'ew "7lCommand("7l$ Connection)
ret;alue = Command.6ecute'on<uer0()
"#at is .D+.NET Dataset
The #,.NET ,ata-et contains ,ataTable%ollection and their ,ata2elation%ollection . )t
represents a collection of data retrieved from the ,ata -ource. We can use ,ataset in
combination with ,ata#dapter class. The ,ata-et ob9ect offers a disconnected data source
architecture. The ,ataset can wor" with the data it contain, without "nowing the source of the
data coming from. That is , the ,ataset can wor" with a disconnected mode from its ,ata
-ource . )t gives a better advantage over ,ata2eader , because the ,ata2eader is wor"ing only
with the connection oriented ,ata -ources.
The ,ataset contains the copy of the data we re*uested. The ,ataset contains more than one
Table at a time. We can set up ,ata 2elations between these tables within the ,ata-et. The data
set may comprise data for one or more members, corresponding to the number of rows.
The ,ata#dapter ob9ect allows us to populate ,ataTables in a ,ata-et. We can use !ill method
of the ,ata#dapter for populating data in a ,ataset. The ,ata-et can be filled either from a data
source or dynamically. # ,ata-et can be saved to an >M/ file and then loaded bac" into
memory very easily. The following lin"s shows more information of ,ataset in details.
*o( to Dataset (it# S2l Ser0er
The ,ata-et contains the copy of the data we re*uested through the -P/ statement. We can use
,ataset in combination with -*l,ata#dapter class . The -*l,ata#dapter ob9ect allows us to
populate ,ata Tables in a ,ata-et. We can use !ill method in the -*l,ata#dapter for populating
data in a ,ataset.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im i s Inte$er
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Rour SC1 Statement &ere.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to Dataset (it# +LEDB Data Source
The ,ata-et contains the copy of the data we re*uested through the -P/ statement. We can use
,ataset in combination with le,b,ata#dapter class . The le,b,ata#dapter ob9ect allows us
to populate ,ata Tables in a ,ata-et. We can use !ill method in the le,b,ata#dapter for
populating data in a ,ataset.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im ds s -e) (ataSet
(im s:l s Strin$
(im i s Inte$er
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere.
connection , -e) Ole(bConnection(connetionStrin$%
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(s:l" connection%
oledbdapter.Fill(ds%
oledbdapter.(ispose(%
connection.Close(%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
Searc# Ta$les in a Dataset S2l Ser0er
The ,ata-et contains ,ataTable%ollection and their ,ata2elation%ollection. The
,ataTable%ollection contains :ero or more ,ataTable ob9ects. The ,ataset may comprise data
for one or more members, corresponding to the number of rows. The -*l,ata#dapter ob9ect
allows us to populate ,ataTables in a ,ata-et.
)n some situations we have to find how many tables inside the ,ataset b9ect contains . The
following VB.NET source code shows how to find the tables inside the ,ataset.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im tables s (ata'able
(im i s Inte$er
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Rour SC1 Statement &ere.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .SC1 'emp 'able.%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
For #ac4 tables In ds.'ables
5s$Bo*(tables.'able-ame%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
Searc# Ta$les in a Dataset +LEDB Data Source
The ,ata-et contains ,ataTable%ollection and their ,ata2elation%ollection. The
,ataTable%ollection contains :ero or more ,ataTable ob9ects. The data inside Table is in the
form of 2ows and %olumns . The le,b,ata#dapter ob9ect allows us to populate ,ataTables in
a ,ata-et.
)n some situations we have to find how many tables inside the ,ataset b9ect contains . The
following VB.NET source code shows how to find the tables inside the ,ataset.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im ds s -e) (ataSet
(im s:l s Strin$
(im i s Inte$er
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere.
connection , -e) Ole(bConnection(connetionStrin$%
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(s:l" connection%
oledbdapter.Fill(ds" .O1#(B 'emp 'able.%
oledbdapter.(ispose(%
connection.Close(%
For i , ; 'o ds.'ables.Count 2 1
5s$Bo*(ds.'ables(i%.'able-ame%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
Dataset ta$le ro( count in S%L Ser0er
The ,ata-et contains copy of the data we re*uested through the -P/ statement. The ,ata-et
consists of ,ataTable%ollection and their ,ata2elation%ollection. The ,ataTable%ollection
contains :ero or more ,ataTable ob9ects. The data set may comprise data for one or more
members, corresponding to the number of rows. The following VB.NET source code shows how
to find the number of rows in a table that resides in the ,ataset.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Rour SC1 Statement &ere.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .SC1 'emp 'able.%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
5s$Bo*(.-umber o3 ro)(s% 2 . A ds.'ables(;%.6o)s.Count%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
Dataset ta$le ro( count 3 +LEDB Data Source
The ,ata-et contains copy of the data we re*uested through the -P/ statement. The ,ata-et
consists of ,ataTable%ollection and their ,ata2elation%ollection. The ,ataTable%ollection
contains :ero or more ,ataTable ob9ects. The data inside Table is in the form of 2ows and
%olumns . The following VB.NET source code shows how to find the number of rows in a table
that resides in the ,ataset from /E,B ,ata -ource.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im ds s -e) (ataSet
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere.
connection , -e) Ole(bConnection(connetionStrin$%
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(s:l" connection%
oledbdapter.Fill(ds" .O1#(B 'emp 'able.%
oledbdapter.(ispose(%
connection.Close(%
5s$Bo*(.number o3 6o)(s% 2 . A ds.'ables(;%.6o)s.Count%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to -nd column de-nition 3 S2l Ser0er
,ataset represents a collection of data retrieved from the ,ata -ource. The ,ataset can wor"
with the data it contains, without "nowing the source of the data coming from. The
-*l,ata#dapter ob9ect allows us to populate ,ataTable in a ,ata-et. We can use !ill method in
the -*l,ata#dapter for populating data in a ,ataset. The ,ataset can contains more than one
Table at a time. The data inside Table is in the form of 2ows and %olumns .
)n some situations we have to find the column headers in a ,ataTable. There is a
%olumns%ollection ob9ect in the ,atatable hold the column ,efinitions.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dt s (ata'able
(im column s (ataColumn
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Rour SC1 Statement &ere.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .SC1 'emp 'able.%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dt , ds.'ables(;%
For #ac4 column In dt.Columns
5s$Bo*(column.Column-ame%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to -nd column de-nition 3 +LEDB Data Source
,ataset represents a collection of data retrieved from the ,ata -ource.. The le,b,ata#dapter
ob9ect allows us to populate ,ataTable in a ,ata-et. We can use !ill method in the
le,b,ata#dapter for populating data in a ,ataset. The ,ataset can contain more than one
Table at a time. The data set may comprise data for one or more members, corresponding to the
number of rows.
)n some situations we have to find the column headers in a ,ataTable. There is a
%olumns%ollection ob9ect in the ,atatable hold the column ,efinitions.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im ds s -e) (ataSet
(im dt s (ata'able
(im s:l s Strin$
(im i s Inte$er
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
s:l , .Rour SC1 Statement &ere.
connection , -e) Ole(bConnection(connetionStrin$%
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(s:l" connection%
oledbdapter.Fill(ds" .O1#(B 'emp 'able.%
oledbdapter.(ispose(%
connection.Close(%
dt , ds.'ables(;%
For i , ; 'o dt.Columns.Count 2 1
5s$Bo*(dt.Columns(i%.Column-ame%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to create DataSet (it#out Data$se
,ataset represents a collection of data retrieved from the ,ata -ource. The ,ata-et contains
,ataTable%ollection and their ,ata2elation%ollection. The ,ataTable%ollection contains :ero or
more ,ataTable ob9ects. The data set may comprise data for one or more members,
corresponding to the number of rows. We can fill the data in ,ataset without calling -P/
statements. !or that we manually create a ,ataTable and add data in it.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im ds s -e) (ataSet
(im dt s (ata'able
(im dr s (ata6o)
(im idCoulumn s (ataColumn
(im nameCoulumn s (ataColumn
(im i s Inte$er
dt , -e) (ata'able(%
idCoulumn , -e) (ataColumn(.I(." 'ype.9et'ype(.System.IntHE.%%
nameCoulumn , -e) (ataColumn(.-ame." 'ype.9et'ype(.System.Strin$.%%
dt.Columns.dd(idCoulumn%
dt.Columns.dd(nameCoulumn%
dr , dt.-e)6o)(%
dr(.I(.% , 1
dr(.-ame.% , .-ame1.
dt.6o)s.dd(dr%
dr , dt.-e)6o)(%
dr(.I(.% , E
dr(.-ame.% , .-ameE.
dt.6o)s.dd(dr%
ds.'ables.dd(dt%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(;%.6o)s(i%.Item(1%%
-e*t i
#nd Sub
#nd Class
*o( to multiple ta$les in Dataset 3 S2l Ser0er
The ,ata-et contains ,ataTable%ollection and their ,ata2elation%ollection. The
,ataTable%ollection contains :ero or more ,ataTable ob9ects. The -*l,ata#dapter ob9ect allows
us to populate ,ataTables in a ,ata-et. We can use !ill method in the -*l,ata#dapter for
populating data in a ,ataset.
We can populate ,ataset with more than one table at a time using -*l,ata#dapter b9ect . The
following VB.NET source code shows how to a single -*l,ata#dapter fill ,ataset with multiple
tables.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im i s Inte$er
(im 3irstS:l s Strin$
(im secondS:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
3irstS:l , .Rour First SC1 Statement &ere.
secondS:l , .Rour Second SC1 Statement &ere.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(3irstS:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .First 'able.%
adapter.SelectCommand.Command'e*t , secondS:l
adapter.Fill(ds" .Second 'able.%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
Dretrieve 3irst table data
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
Dretrieve second table data
For i , ; 'o ds.'ables(1%.6o)s.Count 2 1
5s$Bo*(ds.'ables(1%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(1%.6o)s(i%.Item(1%%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
s@l # )Jour A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to multiple ta$les in Dataset 3 +LEDB Data
Source
The ,ata-et contains ,ataTable%ollection and their ,ata2elation%ollection. The
,ataTable%ollection contains :ero or more ,ataTable ob9ects. The le,b,ata#dapter ob9ect
allows us to populate ,ataTables in a ,ata-et. We can use !ill method in the le,b,ata#dapter
for populating data in a ,ataset. We can populate ,ataset with more than one table at a time
using le,b,ata#dapter b9ect . The following VB.NET source code shows how to a single
le,b,ata#dapter fill ,ataset with multiple tables.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im ds s -e) (ataSet
(im 3irstS:l s Strin$
(im secondS:l s Strin$
(im i s Inte$er
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
3irstS:l , .Rour First SC1 Statement &ere.
secondS:l , .Rour Second SC1 Statement &ere.
connection , -e) Ole(bConnection(connetionStrin$%
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(3irstS:l" connection%
oledbdapter.Fill(ds" .First 'able.%
oledbdapter.SelectCommand.Command'e*t , secondS:l
oledbdapter.Fill(ds" .Second 'able.%
oledbdapter.(ispose(%
connection.Close(%
Dretrieve 3irst table data
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
Dretrieve second table data
For i , ; 'o ds.'ables(1%.6o)s.Count 2 1
5s$Bo*(ds.'ables(1%.6o)s(i%.Item(;% A . 22 . A
ds.'ables(1%.6o)s(i%.Item(1%%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
$irst@l # )Jour 4irst A; tatement =ere)
second@l # )Jour econd A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to add relations $et(een ta$les in a Dataset
The ,ata-et contains ,ataTable%ollection and their ,ata2elation%ollection. The
,ata-et.2elations property is an instance of the ,ata2elations%ollection b9ect. We can create
parent child data relations between ,ataTable using ,atarelation b9ect. We can relate one or
more column from different tables using ,ata2elation b9ect . The columns involved in the
,ata2elation should be identical data types. That is the parent and child column should be
similar ,ata Types.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im 3irstS:l s Strin$
(im secondS:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
3irstS:l , .Rour First SC1 Statement &ere.
secondS:l , .Rour Second SC1 Statement &ere.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(3irstS:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .'able1.%
adapter.SelectCommand.Command'e*t , secondS:l
adapter.Fill(ds" .'ableE.%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
Dcreatin$ data relations
(im relation s (ata6elation
(im table1Column s (ataColumn
(im tableEColumn s (ataColumn
Dretrieve column
table1Column , ds.'ables(.'able1.%.Columns(;%
tableEColumn , ds.'ables(.tableE.%.Columns(;%
Drelatin$ tables
relation , -e) (ata6elation(.relation." table1Column"
tableEColumn%
Dassi$n relation to dataset
ds.6elations.dd(relation%
5s$Bo*(.(ata relation completed.%
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
$irst@l # )Jour 4irst A; tatement =ere)
second@l # )Jour econd A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to merge ta$les in a Dataset 3 S2l Ser0er
The ,ata-et contains copy of the data we re*uested through the -P/ statement. The
-*l,ata#dapter ob9ect allows us to populate ,ataTable in a ,ata-et. We can use !ill method in
the -*l,ata#dapter for populating data in a ,ataset. We can populate ,ataset with more than
one table at a time using -*l,ata#dapter b9ect. The ,ataTable%ollection contains :ero or more
,ataTable ob9ects.
)n some situation we want to combine the result of multiple -P/ *uery as a single result set. )n
that case we can use the ,ataset6s Merge method for doing this. The tables involved in the merge
should be identical, that is the columns are similar data types .
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dt s (ata'able
(im 3irstS:l s Strin$
(im secondS:l s Strin$
(im i s Inte$er
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
3irstS:l , .Rour First SC1 Statement &ere.
secondS:l , .Rour Second SC1 Statement &ere.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(3irstS:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .'able(;%.%
adapter.SelectCommand.Command'e*t , secondS:l
adapter.Fill(ds" .'able(1%.%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
ds.'ables(;%.5er$e(ds.'ables(1%%
dt , ds.'ables(;%
For i , ; 'o dt.6o)s.Count 2 1
5s$Bo*(dt.6o)s(i%.Item(;% A . 22 . A dt.6o)s(i%.Item(1%%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )Data ource#erverNameIInitial 6atalog#DatabaseNameILser
ID#LserNameI2ass9ord#2ass9ord)
$irst@l # )Jour 4irst A; tatement =ere)
second@l # )Jour econd A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to merge ta$les in a Dataset 3 +LEDB Data
Source
The ,ata-et contains copy of the data we re*uested through the -P/ statement. The
le,b,ata#dapter ob9ect allows us to populate ,ataTable in a ,ata-et. We can use !ill method
in the le,b,ata#dapter for populating data in a ,ataset. We can populate ,ataset with more
than one table at a time using le,b,ata#dapter b9ect. The ,ataTable%ollection contains :ero
or more ,ataTable ob9ects. )n some situation we want to combine the result of multiple -P/
*uery results as a single result set. )n that case we can use the ,ataset6s Merge method for doing
this. The tables involved in the merge should be identical. The following VB.NET source code
shows how to merge the tables from two different dataset.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im ds1 s -e) (ataSet
(im dsE s -e) (ataSet
(im dt s (ata'able
(im 3irstS:l s Strin$
(im secondS:l s Strin$
(im i s Inte$er
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
3irstS:l , .Rour First SC1 Statement &ere.
secondS:l , .Rour Second SC1 Statement &ere.
connection , -e) Ole(bConnection(connetionStrin$%
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(3irstS:l" connection%
oledbdapter.Fill(ds1" .First 'able.%
oledbdapter.SelectCommand.Command'e*t , secondS:l
oledbdapter.Fill(dsE" .Second 'able.%
oledbdapter.(ispose(%
connection.Close(%
ds1.'ables(;%.5er$e(dsE.'ables(;%%
dt , ds1.'ables(;%
For i , ; 'o dt.6o)s.Count 2 1
5s$Bo*(dt.6o)s(i%.Item(;% A . 22 . A dt.6o)s(i%.Item(1%%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
connetiontring # )2rovider#,icroso$t.Fet.5;EDB.+.(IData ource#Jour mdb $ilenameI)
$irst@l # )Jour 4irst A; tatement =ere)
second@l # )Jour econd A; tatement =ere)
?ou have to replace the string with your real time variables.
*o( to populate a com$o $ox !rom a dataset in
VB.Net
The ,ata-et consists of a collection of ,ataTable ob9ects that you can relate to each other with
,ata2elation ob9ects. The VB.Net -*l,ata#dapter ob9ect allows us to populate ,ata Tables in a
,ata-et. #lso we can populate a combo bo+ from a dataset values.
Combo:o1..ata"ource = ds.Tables(0)
Combo:o1.;alue-ember = 1au%id1
Combo:o1..is2la0-ember = 1au%lname1
The following VB.Net program fetch the values from database and store it in a dataset and later
bind to a combobo+.
Do$nload Source !ode
Print Source !ode
Imports System.(ata
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Form1_1oad(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles 5yBase.1oad
(im connetionStrin$ s Strin$ , -ot4in$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter(%
(im ds s -e) (ataSet(%
(im i s Inte$er , ;
(im s:l s Strin$ , -ot4in$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,databasenameOFser I(,useridOPass)ord,yourpass)ord.
s:l , .select au_id"au_lname 3rom aut4ors.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
ComboBo*1.(ataSource , ds.'ables(;%
ComboBo*1.Value5ember , .au_id.
ComboBo*1.(isplay5ember , .au_lname.
Catc4 e* s #*ception
5essa$eBo*.S4o)(.Can not open connection 7 .%
#nd 'ry
#nd Sub
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
5s$Bo*(ComboBo*1.'e*t N . 22 . N ComboBo*1.SelectedValue%
#nd Sub
#nd Class
#o( many ta$les exist in a data$ase 3 VB.NET
# table is responsible for storing data in the database. # table is a set of data elements that is
organi:ed using a model of vertical columns and hori:ontal rows.# database is made up of many
lin"ed tables of rows and columns, each containing specific data.
)n many situations you should find the no. of tables e+ist in your database. Everything about your
-P/ -erver database is stored in its system tables.
"elect .&"T&'CT(name) FR9- s0s.Tables
2eturns a row for each table ob9ect, currently only with sys.ob9ects.type F 3. -ystem tables
should not be altered directly by any user
Do$nload Source !ode
Print Source !ode
Imports System.(ata
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im tables s (ata'able
(im i s Inte$er
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select (IS'I-C'(name% F6O5 sys.'ables.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;%%
-e*t
Catc4 e* s #*ception
5s$Bo*(.Can not open connection 7 .%
#nd 'ry
#nd Sub
#nd Class
Dataadapter (it# dataset 3 s2l se0er
-*l,ata#dapter provides the communication between the ,ataset and the ,ata -ource with the
help of -*l%onnection b9ect . The -*l%onnection b9ect has no information about the data it
retrieves . -imilarly a ,ataset has no "nowledge of the ,ata -ource where the data coming from.
-o the -*l,ata#dapter manage the communication between these two b9ects.
The -*l,ata#dapter ob9ect allows us to populate ,ata Tables in a ,ata-et. We can use !ill
method of the -*l,ata#dapter for populating data in a ,ataset. The following source code shows
a simple program that uses -*l,ata#dapter to retrieve data from ,ata -ource with the help of
-*l%onnection ob9ect and populate the data in a ,ataset.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im adapter s S:l(atadapter
(im ds s -e) (ataSet
(im i s Inte$er
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
adapter , -e) S:l(atadapter(.Rour SC1 Statement &ere."
connection%
adapter.Fill(ds%
connection.Close(%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter (it# dataset 3 +LEDB Data Source
le,b,ata#dapter provides the communication between the ,ataset and the ,ata -ource with
the help of le,b%onnection b9ect . The le,b%onnection b9ect has no information about
the data it retrieves . -imilarly a ,ataset has no "nowledge of the ,ata -ource where the data
coming from. -o the le,b,ata#dapter manage the communication between these two b9ects.
The le,b,ata#dapter ob9ect allows us to populate ,ata Tables in a ,ata-et. We can use !ill
method of the le,b,ata#dapter for populating data in a ,ataset. The following source code
shows a simple program that uses le,b,ata#dapter to retrieve data from ,ata -ource with the
help of le,b%onnection ob9ect and populate the data in a ,ataset.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im ds s -e) (ataSet
(im i s Inte$er
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
connection , -e) Ole(bConnection(connetionStrin$%
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(.Rour SC1 Statement &ere.%
oledbdapter.Fill(ds%
oledbdapter.(ispose(%
connection.Close(%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;%%
-e*t
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter SelectCommand 3 S2l Ser0er
-*l,ata#dapter is a part of the #,.NET ,ata $rovider. -*l,ata#dapter provides the
communication between the ,ataset and the ,ata -ource with the help of -*l%onnection
b9ect .The -*l,ata#dapter wor"s with the ,ata-et to provide a disconnected data retrieval
mechanism.
The -elect%ommand property of the -*l,ata#dapter is a %ommand ob9ect that retrieves data
from the data source. The following program shows the -*l,ata#dapter using its
-elect%ommand property to retrieve the data from the ,ata -ource.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im i s Inte$er
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
adapter.SelectCommand , -e) S:lCommand(.Rour SC1 Statement &ere."
connection%
adapter.Fill(ds%
connection.Close(%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter SelectCommand 3 +LEDB Data Source
le,b,ata#dapter is a part of the #,.NET ,ata $rovider. le,b,ata#dapter provides the
communication between the ,ataset and the ,ata -ource with the help of le,b%onnection
b9ect. The le,b,ata#dapter wor"s with the ,ata-et to provide a disconnected data retrieval
mechanism.
The -elect%ommand property of the le,b,ata#dapter is a %ommand ob9ect that retrieves data
from the data source. The following program shows the le,b,ata#dapter using its
-elect%ommand property to retrieve the data from the ,ata -ource.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s -e) Ole(b(atadapter
(im ds s -e) (ataSet
(im i s Inte$er
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
connection , -e) Ole(bConnection(connetionStrin$%
'ry
connection.Open(%
oledbdapter.SelectCommand , -e) Ole(bCommand(.Rour SC1 Statement
&ere." connection%
oledbdapter.Fill(ds%
oledbdapter.(ispose(%
connection.Close(%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(;%%
-e*t
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter InsertCommand 3 S2l Ser0er
-*l,ata#dapter provides the communication between the ,ataset and the ,ata -ource with the
help of -*l%onnection b9ect . The )nsert%ommand in -*l,ata#dapter b9ect manages to insert
the data in the specified ,ata -ource .
)n the following -ource %ode shows how to insert data in the ,ata -ource using -*l,ata#dapter
and -*l%ommand ob9ect. pen a connection to the ,ata -ource with the help of -*l%onnection
ob9ect and create a -*l%ommand ob9ect with insert -P/ statement, and assign the -*l%ommand
to the -*l,ata#dapter6s )nsert%ommand.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im adapter s -e) S:l(atadapter
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
connection , -e) S:lConnection(connetionStrin$%
s:l , .insert into product (Product_id"Product_name"Product_price%
values(K"DProductKD"K;;%.
'ry
connection.Open(%
adapter.InsertCommand , -e) S:lCommand(s:l" connection%
adapter.InsertCommand.#*ecute-onCuery(%
5s$Bo*(.6o) inserted 77 .%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter InsertCommand 3 +LEDB Data Source
le,b,ata#dapter provides the communication between the ,ataset and the ,ata -ource with
the help of le,b%onnection b9ect . The )nsert%ommand in le,b,ata#dapter b9ect
manages to insert the data in the specified ,ata -ource .
)n the following -ource %ode shows how to insert data in the ,ata -ource using
le,b,ata#dapter and le,b%ommand ob9ect. pen a connection to the ,ata -ource with the
help of le,b%onnection ob9ect and create an le,b%ommand ob9ect with insert -P/
statement, and assign the le,b%ommand to the -*l,ata#dapter6s )nsert%ommand.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s -e) Ole(b(atadapter
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
connection , -e) Ole(bConnection(connetionStrin$%
s:l , .insert into user values(Duser1D"Dpass)ord1D%.
'ry
connection.Open(%
oledbdapter.InsertCommand , -e) Ole(bCommand(s:l" connection%
oledbdapter.InsertCommand.#*ecute-onCuery(%
5s$Bo*(.6o)(s% Inserted 77 .%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter /pdateCommand 3 S2l Ser0er
-*l,ata#dapter is a part of the #,.NET ,ata $rovider. The )nsert%ommand, the
3pdate%ommand, and the ,elete%ommand properties of the -*l,ata#dapter ob9ect update the
database with the data modifications, that are run on a ,ata-et ob9ect.
The following code samples that demonstrate how to use the -*l,ata#dapter ob9ect to update a
-P/ -erver database using 3pdate%ommand properties in -*l,ata#dapter.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im adapter s -e) S:l(atadapter
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
connection , -e) S:lConnection(connetionStrin$%
s:l , .update product set product_price , 1;;1 )4ere Product_name
,DProductKD.
'ry
connection.Open(%
adapter.FpdateCommand , connection.CreateCommand
adapter.FpdateCommand.Command'e*t , s:l
adapter.FpdateCommand.#*ecute-onCuery(%
5s$Bo*(.6o) updated 77 .%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter /pdateCommand 3 +LEDB Data Source
le,b,ata#dapter is a part of the #,.NET ,ata $rovider. The )nsert%ommand, the
3pdate%ommand, and the ,elete%ommand properties of the le,b,ata#dapter ob9ect update
the ,ata -ource with the data modifications that are run on a ,ata-et ob9ect.
The following code samples that demonstrate how to use the le,b,ata#dapter ob9ect to update
an /E,B ,ata -ource using 3pdate%ommand properties in le,b,ata#dapter.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s -e) Ole(b(atadapter
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
connection , -e) Ole(bConnection(connetionStrin$%
s:l , .update Fsers set Pass)ord , Dne) pass)ordD )4ere FserI( ,
Duser1D.
'ry
connection.Open(%
oledbdapter.FpdateCommand , connection.CreateCommand
oledbdapter.FpdateCommand.Command'e*t , s:l
oledbdapter.FpdateCommand.#*ecute-onCuery(%
5s$Bo*(.6o)(s% Fpdated 77 .%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter DeleteCommand 3 S2l Ser0er
-*l,ata#dapter is a part of the #,.NET ,ata $rovider. The )nsert%ommand, the
3pdate%ommand, and the ,elete%ommand properties of the -*l,ata#dapter ob9ect update the
database with the data modifications, that are run on a ,ata-et ob9ect.
The following code samples that demonstrate how to use the -*l,ata#dapter ob9ect to update a
-P/ -erver database using 3pdate%ommand properties in -*l,ata#dapter.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im adapter s -e) S:l(atadapter
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
connection , -e) S:lConnection(connetionStrin$%
s:l , .delete product )4ere Product_name ,DProductKD.
'ry
connection.Open(%
adapter.(eleteCommand , connection.CreateCommand
adapter.(eleteCommand.Command'e*t , s:l
adapter.(eleteCommand.#*ecute-onCuery(%
5s$Bo*(.6o)(s% deleted 77 .%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter DeleteCommand 3 +LEDB Data Source
le,b,ata#dapter is a part of the #,.NET ,ata $rovider. The le,b,ata#dapter wor"s with
the ,ata-et to provide a disconnected data retrieval mechanism. The )nsert%ommand,
3pdate%ommand, and ,elete%ommand properties of the le,b,ata#dapter are %ommand
ob9ects that manage updates to the specified data source according to modifications.
The following -ource %ode shows how to perform delete data from a database using
,elete%ommand property of le,b,ata#dapter.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s -e) Ole(b(atadapter
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
connection , -e) Ole(bConnection(connetionStrin$%
s:l , .delete 3rom Fsers )4ere FserI( , Duser1D.
'ry
connection.Open(%
oledbdapter.(eleteCommand , connection.CreateCommand
oledbdapter.(eleteCommand.Command'e*t , s:l
oledbdapter.(eleteCommand.#*ecute-onCuery(%
5s$Bo*(.6o)(s% (eleted 77 .%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter (it# CommandBuilder 3 S2l Ser0er
The ,ata#dapter is a part of the #,.NET ,ata $rovider. #,.NET ,ata#dapter is used to
manage four separate %ommand ob9ects. The )nsert%ommand, the 3pdate%ommand, and the
,elete%ommand properties of the -*l,ata#dapter ob9ect update the database with the data
modifications that are run on a ,ata-et ob9ect. The -*l%ommand ob9ects that are assigned to
these properties can be created manually in code or automatically generated by using the
-*l%ommandBuilder ob9ect.
The -*l%ommandBuilder opens the %onnection associated with the ,ata#dapter and ma"es a
round trip to the server each and every time it6s as"ed to construct the action *ueries. )t closes the
%onnection when it6s done. The following -ource %ode demonstrate how to use the
-*l,ata#dapter ob9ect to update a -P/ -erver database with data modifications that are run on a
,ata-et ob9ect that is populated with data from a table in the database using
-*l%ommandBuilder ob9ect.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im adapter s S:l(atadapter
(im cmdBuilder s S:lCommandBuilder
(im ds s -e) (ataSet
(im s:l s Strin$
(im i s IntHE
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
connection , -e) S:lConnection(connetionStrin$%
s:l , .select P 3rom Product.
'ry
connection.Open(%
adapter , -e) S:l(atadapter(s:l" connection%
cmdBuilder , -e) S:lCommandBuilder(adapter%
adapter.Fill(ds%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
ds.'ables(;%.6o)s(i%.Item(E% , ds.'ables(;%.6o)s(i%.Item(E% N
1;;
-e*t
adapter.Fpdate(ds.'ables(;%%
connection.Close(%
5s$Bo*(.(ata updated 7 .%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter (it# CommandBuilder 3 +LEDB
The le,b,ata#dapter is a part of the #,.NET ,ata $rovider. le,b,ata#dapter is used to
manage four separate %ommand ob9ects. The )nsert%ommand, the 3pdate%ommand, and the
,elete%ommand properties of the le,b,ata#dapter ob9ect update the database with the data
modifications that are run on a ,ata-et ob9ect. The le,b%ommand ob9ects that are assigned to
these properties can be created manually in code or automatically generated by using the
le,b%ommandBuilder ob9ect.
The le,b%ommandBuilder opens the %onnection associated with the le,b,ata#dapter and
ma"es a round trip to the server each and every time it6s as"ed to construct the action *ueries. )t
closes the %onnection when it6s done. The following -ource %ode demonstrate how to use the
le,b,ata#dapter ob9ect to update a /E,B ,ata -ource with data modifications that are run
on a ,ata-et ob9ect that is populated with data from a table in the database using
le,b%ommandBuilder ob9ect.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im oledbCmdBuilder s Ole(bCommandBuilder
(im ds s -e) (ataSet
(im i s Inte$er
(im s:l s Strin$
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
connection , -e) Ole(bConnection(connetionStrin$%
s:l , .select P 3rom tblFsers.
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(s:l" connection%
oledbCmdBuilder , -e) Ole(bCommandBuilder(oledbdapter%
oledbdapter.Fill(ds%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
ds.'ables(;%.6o)s(i%.Item(E% , .ne)eamilTemail.com.
-e*t
oledbdapter.Fpdate(ds.'ables(;%%
connection.Close(%
5s$Bo*(.#mail address updates 7.%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter (it# Data4ridVie( 3 S2l Ser0er
-*l,ata#dapter provides the communication between the ,ataset and the ,ata -ource with the
help of -*l%onnection b9ect . The -*l%onnection b9ect has no information about the data it
retrieves . -imilarly a ,ataset has no "nowledge of the ,ata -ourcewhere the data coming from.
-o the -*l,ata#dapter manage the communication between these two b9ects. The
TableMapping %ollections help the -*l,ata#dapter to do this tas".
The )nsert%ommand, the 3pdate%ommand, and the ,elete%ommand properties of the
-*l,ata#dapter ob9ect update the database with the data modifications that are run on a ,ata-et
ob9ect. The following source code demonstrate how to update a ,ataset through -*l,ata#dapter
using a ,ata7ridView. !or running this source code , open a new VB.NET pro9ect and drag two
buttons and a ,ata7ridView in the default formA and copy and paste the following -ource %ode.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im adapter s S:l(atadapter
(im cmdBuilder s S:lCommandBuilder
(im ds s -e) (ataSet
(im c4an$es s (ataSet
(im s:l s Strin$
(im i s IntHE
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
connection , -e) S:lConnection(connetionStrin$%
S:l , .select P 3rom Product.
'ry
connection.Open(%
adapter , -e) S:l(atadapter(S:l" connection%
adapter.Fill(ds%
connection.Close(%
(ata9ridVie)1.(ata Source, ds.'ables(;%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles ButtonE.Click
'ry
cmdBuilder , -e) S:lCommandBuilder(adapter%
c4an$es , ds.9etC4an$es(%
I3 c4an$es Is-ot -ot4in$ '4en
adapter.Fpdate(c4an$es%
#nd I3
5s$Bo*(.C4an$es (one.%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
Dataadapter (it# Data4ridVie( 3 +LEDB
le,b,ata#dapter provides the communication between the ,ataset and the /E,B ,ata
-ource with the help of le,b%onnection b9ect . The le,b%onnection b9ect has no
information about the data it retrieves . -imilarly a ,ataset has no "nowledge of the ,ata -ource
where the data coming from. -o the le,b,ata#dapter manage the communication between
these two b9ects. The TableMapping %ollection help the le,b,ata#dapter to do this tas".
The )nsert%ommand, the 3pdate%ommand, and the ,elete%ommand properties of the
le,b,ata#dapter ob9ect update the database with the data modifications that are run on a
,ata-et ob9ect. The following source code demonstrate how to update a ,ataset through
le,b,ata#dapter using a ,ata7ridView. !or running this source code , open a new VB.NET
pro9ect and drag two buttons and a ,ata7ridView in the default formA and copy and paste the
following -ource %ode.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
(im connetionStrin$ s Strin$
(im connection s Ole(bConnection
(im oledbdapter s Ole(b(atadapter
(im oledbCmdBuilder s Ole(bCommandBuilder
(im ds s -e) (ataSet
(im c4an$es s (ataSet
(im i s Inte$er
(im s:l s Strin$
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
connetionStrin$ , .Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,Rour
mdb 3ilenameO.
connection , -e) Ole(bConnection(connetionStrin$%
S:l , .select P 3rom tblFsers.
'ry
connection.Open(%
oledbdapter , -e) Ole(b(atadapter(S:l" connection%
oledbdapter.Fill(ds%
(ata9ridVie)1.(ata Source, ds.'ables(;%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles ButtonE.Click
'ry
oledbCmdBuilder , -e) Ole(bCommandBuilder(oledbdapter%
c4an$es , ds.9etC4an$es(%
I3 c4an$es Is-ot -ot4in$ '4en
oledbdapter.Fpdate(ds.'ables(;%%
#nd I3
ds.cceptC4an$es(%
5s$Bo*(.Save c4an$es.%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
*o( to create a DataVie(
The ,ataView provides different views of the data stored in a ,ataTable. ,ataView can be used
to sort, filter, and search in a ,ataTable , additionally we can add new rows and modify the
content in a ,ataTable. ,ataViews can be created and configured both design time and run time .
%hanges made to a ,ataView affect the underlying ,ataTable automatically, and changes made
to the underlying ,ataTable automatically affect any ,ataView ob9ects that are viewing the
,ataTable.
We can create ,ataView in two different ways. We can use the ,ataView constructor, or you can
create a reference to the ,efaultView property of the ,ataTable. The ,ataView constructor can
be empty, or it can ta"e either a ,ataTable as a single argument, or a ,ataTable along with filter
criteria, sort criteria, and a row state filter.
dataVie$ 5 dataSet.Tables1>3.De'aultVie$
The following source code shows how to create a ,ataView in VB.NET. %reate a new VB.NET
pro9ect and drag a ,ata7ridView and a Button on default !orm !ormA , and copy and paste the
following -ource %ode on button clic" event.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dv s (ataVie)
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .Create (ataVie).%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dv , ds.'ables(;%.(e3aultVie)
(ata9ridVie)1.(ataSource , dv
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
*o( to sort DataVie(
The ,ataView provides different views of the data stored in a ,ataTable. ,ataView can be used
to sort, filter, and search data in a ,ataTable , additionally we can add new rows and modify the
content in a ,ataTable. ,ataViews can be created and configured at both design time and run
time . %hanges made to a ,ataView affect the underlying ,ataTable automatically, and changes
made to the underlying ,ataTable automatically affect any ,ataView ob9ects that are viewing
that ,ataTable.
We can sort single or multiple fields in a ,ataView , also we can specify the sort order li"e #-%
0ascending1 and ,E-% 0descending1 . The following e+ample creates a View and apply sort on
the column $roductE$rice in descending order. %reate a new VB.NET pro9ect and drag a
,ata7ridView and a Button on default !orm !ormA , and copy and paste the following -ource
%ode on button clic" event.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dv s (ataVie)
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .Sort (ataVie).%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dv , -e) (ataVie)(ds.'ables(;%" .Product_Price S 1;;."
.Product_Price (esc." (ataVie)6o)State.Current6o)s%
(ata9ridVie)1.(ataSource , dv
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
*o( to Filter DataVie(
,ataView enables you to create different views of the data stored in a ,ataTable. That is we can
customi:e the views of data from a ,ataTable. ,ataView can be used to sort, filter, and search a
,ataTable , additionally we can add new rows and modify the content in a ,ataTable. We can
create ,ataView in two ways. Either we can use the ,ataView constructor, or we can create a
reference to the ,efaultView property of the ,ataTable. #lso we can create multiple ,ataViews
for any given ,ataTable.
The following source code creates a view that shows all $roduct ,etails where the $roduct $rice
less than IDD. %reate a new VB.NET pro9ect and drag a ,ata7ridView and a Button on default
!orm !ormA , and copy and paste the following -ource %ode on button clic" event.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dv s (ataVie)
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .Filter (ataVie).%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dv , -e) (ataVie)(ds.'ables(;%" .Product_Price W , I;;."
.Product_-ame." (ataVie)6o)State.Current6o)s%
(ata9ridVie)1.(ataSource , dv
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
*o( to Find a ro( in DataVie(
The ,ataView provides different views of the data stored in a ,ataTable. The constructor for the
,ataView class initiali:es a new instance of the ,ataView class and accepts the ,ataTable as an
argument. We can create ,ataView in two ways. Either we can use the ,ataView constructor, or
we can create a reference to the ,efaultView property of the ,ataTable. We can create multiple
,ataViews for any given ,ataTable.
We can search in a ,ataView according to the sort "ey values by using the !ind method . The
!ind method returns an integer with the inde+ of the ,ata2owView that matches the search
criteria. )f more than one row matches the search criteria, only the inde+ of the first matching
,ata2owView is returned. )f no matches are found, !ind returns .A
Dim index As Inteer 5 DataVie$.&ind16Product;63
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dv s (ataVie)
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
connection , -e) S:lConnection(connectionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .Find 6o) (ataVie).%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dv , -e) (ataVie)(ds.'ables(;%%
dv.Sort , .Product_-ame.
(im inde* s Inte$er , dv.Find(.ProductI.%
I3 inde* , 21 '4en
5s$Bo*(.Item -ot Found.%
#lse
5s$Bo*(dv(inde*%(.Product_id.%.'oStrin$(% A . . A dv(inde*%
(.Product_-ame.%.'oStrin$(%%
#nd I3
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
*o( to add ne( ro(s in DataVie(
The ,ataView provides different views of the data stored in a ,ataTable. ,ataViews can be
created and configured at both design time and run time . We can create ,ataView in two ways.
Either we can use the ,ataView constructor, or we can create a reference to the ,efaultView
property of the ,ataTable. We can create multiple ,ataViews for any given ,ataTable.
We can add new rows in the ,ataView using #ddNew method in the ,ataView. The following
source code shows how to add new row in a ,ataView . %reate a new VB.NET pro9ect and drag
a ,ata7ridView and a Button on default !orm !ormA , and copy and paste the following -ource
%ode on button clic" event.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dv s (ataVie)
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .dd -e).%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dv , -e) (ataVie)(ds.'ables(;%%
(im ne)6o) s (ata6o)Vie) , dv.dd-e)(%
ne)6o)(.Product_I(.% , K
ne)6o)(.Product_-ame.% , .Product K.
ne)6o)(.Product_Price.% , 111
ne)6o).#nd#dit(%
dv.Sort , .product_id.
(ata9ridVie)1.(ataSource , dv
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
*o( to update ro(s in DataVie(
The ,ataView provides different views of the data stored in a ,ataTable. ,ataView can be used
to sort, filter, and search a ,ataTable , additionally we can add new rows and modify the content
in a ,ataTable. We can create ,ataView in two ways. Either we can use the ,ataView
constructor, or we can create a reference to the ,efaultView property of the ,ataTable. #lso we
can create multiple ,ataViews for any given ,ataTable.
We can update the data in a ,ataView . The following source code shows how to update data in a
,ataView . %reate a new VB.NET pro9ect and drag a ,ata7ridView and a Button on default
!orm !ormA , and copy and paste the following -ource %ode on button clic" event.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dv s (ataVie)
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .Fpdate.%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dv , -e) (ataVie)(ds.'ables(;%" .." .Product_-ame."
(ataVie)6o)State.Current6o)s%
(im inde* s Inte$er , dv.Find(.ProductI.%
I3 inde* , 21 '4en
5s$Bo*(.Product not 3ound.%
#lse
dv(inde*%(.Product_-ame.% , .Product11.
5s$Bo*(.Product Fpdated 7.%
#nd I3
(ata9ridVie)1.(ataSource , dv
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
*o( to delete ro(s in DataVie(
The ,ataView provides different views of the data stored in a ,ataTable. ,ataView can be used
to sort, filter, and search data in a ,ataTable , additionally we can add new rows and modify the
content in a ,ataTable. #lso we can delete the data from the ,ataView . The following source
code shows how to delete the data from ,ataView.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dv s (ataVie)
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .(elete 6o).%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dv , -e) (ataVie)(ds.'ables(;%" .." .Product_I(."
(ataVie)6o)State.Current6o)s%
dv.'able.6o)s(H%.(elete(%
(ata9ridVie)1.(ataSource , dv
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
*o( to create a ne( DataTa$le !rom DataVie(
The ,ataView provides different views of the data stored in a ,ataTable. That is we can
customi:e the views of data from a ,ataTable. %hanges made to a ,ataView affect the
underlying ,ataTable automatically, and changes made to the underlying ,ataTable
automatically affect any ,ataView ob9ects that are viewing that ,ataTable. We can create a new
,ataTable from the ,ataView . We can use the ToTable method to copy all the rows and
columns, or a subset of the data into a new ,ataTable.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adapter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im dv s (ataVie)
(im s:l s Strin$
connetionStrin$ , .(ata Source,Server-ameOInitial
Catalo$,(atabase-ameOFser I(,Fser-ameOPass)ord,Pass)ord.
s:l , .Select P 3rom product.
connection , -e) S:lConnection(connetionStrin$%
'ry
connection.Open(%
command , -e) S:lCommand(s:l" connection%
adapter.SelectCommand , command
adapter.Fill(ds" .Copy to (ata'able.%
adapter.(ispose(%
command.(ispose(%
connection.Close(%
dv , -e) (ataVie)(ds.'ables(;%" .Product_Price W, E;;."
.Product_I(." (ataVie)6o)State.Current6o)s%
(im d'able s (ata'able
d'able , dv.'o'able
(ata9ridVie)1.(ataSource , d'able
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
.Net Remoting .rc#itecture
The .NET 2emoting provides an inter.process communication between #pplication ,omains by
using 2emoting !ramewor". The applications can be located on the same computer, different
computers on the same networ", or on computers across separate networ"s. The .NET 2emoting
supports distributed ob9ect communications over the T%$ and 8TT$ channels by using Binary or
-#$ formatters of the data stream.
The main three components of a 2emoting !ramewor" are =
A. 2emotable b9ect.
5. 2emote /istener #pplication . 0listening re*uests for 2emote b9ect1
4. 2emote %lient #pplication . 0ma"es re*uests for 2emote b9ect1
The 2emote b9ect is implemented in a class that derives from ystem.,arshalByRe$5b?ect .
?ou can see the basic wor"flow of .Net 2emoting from the above figure. When a client calls the
2emote method, the client does not call the methods directly . )t receives a pro+y to the remote
ob9ect and is used to invo"e the method on the 2emote b9ect. nce the pro+y receives the
method call from the %lient , it encodes the message using appropriate formatter 0Binary
!ormatter or -#$ !ormatter 1 according to the %onfiguration file. #fter that it sends the call to
the -erver by using selected %hannel 0Tcp%hannel ,8ttp%hannel1. The -erver side channel
receives the re*uest from the pro+y and forwards it to the -erver on 2emoting system, which
locates and invo"es the methods on the 2emote b9ect. When the e+ecution of remote method is
complete, any results from the call are returned bac" to the client in the same way.
Before an ob9ect instance of a 2emotable type can be accessed, it must be created and initiali:ed
by a process "nown as #ctivation. #ctivation is categori:ed in two models , they are %lient.
activated b9ects and -erver.activated b9ects.
2emote #ctivation
The real difference between client.activated and server.activated ob9ects is that a server.activated
ob9ect is not really created when a client instantiates it. )nstead, it is created as needed.
By default the .NET !ramewor" ships with two formatters0Binary !ormatter or -#$
!ormatter 1 and two channels0Tcp%hannel ,8ttp%hannel1.
2emote %hannels
2emote !ormatters
!ormatters and %hannel are configured by using %onfiguration files. )t can be easily %onfigured
by using >M/.based files.
2emote %onfiguration
The .NET 2emoting is easy to use and powerful, largely because it is based on the %ommon
Type -ystem 0%T-1 and the %ommon /anguage 2untime 0%/21. !rom the following lin" , you
can understand .Net 2emoting components in detail.
VB.NET Remoting .pllication
The .NET 2emoting supports ,istributed b9ect communications over the T%$ and 8TT$
transports by using Binary or -#$ representation of the data stream. !or building a 2emoting
application in VB.NET ,you must have an implementation of a 2emotable type, a /istening or
8ost #pplication domain, a %lient or calling application domain, and you must %onfigure the
remoting system in each application domain to use remote activation for the remotable type.
2emotable b9ect
2emote /istener #pplication
2emote %lient #pplication
2emote %onfiguration
Remota$le Type
#ny ob9ect outside the application domain of the caller application should be considered as
2emote b9ect. # 2emote b9ect that should be derived from ,arshalByRe$5b?ect %lass. #ny
ob9ect can be changed into a 2emote b9ect by deriving it from ,arshalByRe$5b?ect . b9ects
without inheriting from ,arshalByRe$5b?ect are called Non.remotable b9ects.
The following e+ample creating a 2emote b9ect in VB.Net, 2emoteTime , which send the
current time to the %lient #pplication using 2emoting !ramewor". The 2emoteTime class is
derived from ,arshalByRe$5b?ect and inside the class it has a method getTime./ which return
the current time from 2emote b9ect.
Do$nload Source !ode
Print Source !ode
Imports System
Public Class 6emote'ime
In4erits 5ars4alBy6e3Ob!ect
Private current'ime s Strin$ , ..

Public Function $et'ime(% s Strin$
current'ime , (ate'ime.-o).'oS4ort'imeStrin$(%
6eturn .6emote Server 'ime / . A current'ime
#nd Function
#nd Class
%opy and paste the above VB.Net source code into a file and save it as 2emoteTime.vb
%ompile the class 2emoteTime.vb into a library using the command.line tools that ship with
the .NET !ramewor" -,M.
#t the command prompt in the directory in which you saved the file, type the following
command=
vbc Qt:library RemoteTime.vb
#fter you compile the 2emoteTime.vb , you will get a file called 2emoteTime.dll in the
directory which you saved the source file.
Remote Listener .pplication
We already created a 2emote Type b9ect 2emoteTime in the previous section. We have to
create a listener b9ect for enable b9ects in other application domains to create instances of this
ob9ect 02emoteTime1 2emotely. When creating a listener b9ect we have to choose and register
a channel for handle the networ"ing protocol and seriali:ation formats and register the Type with
the .NET 2emoting system, so that it can use the channel to listen for re*uests for the Type.
%hannels are b9ects that responsible of handling the networ" protocols and seriali:ation
formats.
)n the following e+ample we are creating a listener application Time/istener . )t will act as a
listener b9ect for the 2emote Type 2emoteTime. The /istener class Time/istener must be able
to find the Time/istener.e+e.config file to load the configuration for the 2emotableType class.
Do$nload Source !ode
Print Source !ode
Imports System
Imports System.6untime.6emotin$
Public Class 'ime1istener
Public S4ared Sub 5ain(%
6emotin$Con3i$uration.Con3i$ure(.'ime1istener.e*e.con3i$.%
Console.+rite1ine(.1istenin$ 3or re:uests 3rom t4e Client. Press #nter
to e*it....%
Console.6ead1ine(%
#nd Sub
#nd Class
%opy and paste the above VB.Net source code into a file and save it as Time/istener.vb.
We have to create additional configuration file to provide the communication information to the
listener b9ect. The configuration file is an >M/ structured file. We can specify the #ctivation
Mode , the 2emote Type , %hannel , port for communication etc. through the configuration file .
%lic" here to download Time/istener.e+e.config .
%ompile the class file Time/istener.vb using the command.line tools that ship with the .NET
!ramewor" -,M.
#t the command prompt in the directory in which you saved the file, type the following
command=
vbc Qr:RemoteTime.dll Time;istener.vb
#fter you compile the Time/istener.vb , you will get a file called Time/istener.e+e in the
directory which you saved the source file
Remote Client .pplication
The %lient application for calling 2emote b9ect6s method in VB.Net is pretty simple and
straight forward. The .NET 2emoting system will intercept the client calls, forward them to the
remote ob9ect, and return the results to the client. The %lient #pplication have to register for the
2emote Type also.
8ere in the %lient application in VB.Net , creating an instance of the 2emote Type, 2emoteTime
b9ect , and call the method getTime./ . #ditionally it uses the configuration file
%lient.e+e.config for the communication information for the 2emoting !ramewor".
Do$nload Source !ode
Print Source !ode
Imports System
Imports System.6untime.6emotin$
Public Class Client
Public S4ared Sub 5ain(%
6emotin$Con3i$uration.Con3i$ure(.Client.e*e.con3i$.%
(im remote'imeOb!ect s -e) 6emote'ime(%
Console.+rite1ine(remote'imeOb!ect.$et'ime(%%
#nd Sub
#nd Class
%opy and paste the above VB.Net source code into a file and save it as %lient.vb.
We have to create additional configuration file to provide the communication information to the
%lient b9ect. The configuration file is a an >M/ structured file. We can specify the 2emote
Type , %hannel , port for communication etc. through the configuration file .
%lic" here to download %lient.e+e.config .
%ompile the class file %lient.vb using the command.line tools that ship with the .NET
!ramewor" -,M.
#t the command prompt in the directory in which you saved the file, type the following
command=
vbc Qr:RemoteTime.dll 6lient.vb
#fter you compile the %lient.vb , you will get a file called %lient.e+e in the directory which you
saved the source file
Compiling and Running Remote .pplication
The .NET 2emoting is one of several ways to establish communication between application
domains using the .NET !ramewor".
The main three components of a 2emoting !ramewor" are a 2emotable b9ect , /istener
#pplication for listening re*uests for remote ob9ect and a %lient #pplication ma"es re*uests for
remote ob9ect. #dditionally you need %onfiguration files for your /istener #pplication and
%lient #pplication.
%ompiling the VB.Net source code files
%reate a new folder -2% and put the three VB.Net source code files in that folder.
A. 2emoteTime.vb
5. Time/istener.vb
4. %lient.vb
#dd the two configuration files in the same folder.
A. Time/istener.e+e.config
5. %lient.e+e.config
%ompile these VB.Net class files using the command.line tools that ship with the .NET
!ramewor" -,M.
vbc Qt:library RemoteTime.vb
vbc Qr:RemoteTime.dll Time;istener.vb
vbc Qr:RemoteTime.dll 6lient.vb
Note= ?ou have to provide the physical path of each source files when you compile the source
code , for e+ample = if the source code files are in the folder c=T-2% , you have to give path li"e
vbc Qr:c:ER6ERemoteTime.dll c:ER6ETime;istener.vb
#fter you complied the VB.Net source code files, you will get additional three files in the -2%
folder. They are =
2emoteTime.dll
Time/istener.e+e
%lient.e+e
To run t%e application
%reate two new folders and give the name li"e Ser"er and !lient respectively.
%opy 2emoteTime.dll , Time/istener.e+e and Time/istener.e+e.config to the -erver folder.
%opy 2emoteTime.dll , %lient.e+e and %lient.e+e.config to the %lient folder.
pen a command prompt on -erver folder and type Time/istener
Then you will get a screen showing G/istening for re*uests from the %lient. $ress Enter to e+it...G
pen a command prompt on %lient folder and type %lient.
Then you will get the current time from remote b9ect.
Now you have done your first .Net 2emoting VB.Net pro9ect successfully . Try to e+plore more
on 2emoting ...
Remoting Con-gurations
%onfiguration provides the necessary information to .Net 2emoting !ramewor" . We can provide
.Net 2emoting configuration parameters in two ways. Either we can provide the information to
the -erver and the %lient directly by program coding or through a Machine.config file. 3sing
configuration file give better advantage over coding because the parameters of remote ob9ect can
be configured without changing any program coding and avoid recompile the source code.
!ollowing are the information provided by configuration file =
,etadata describing the Remote Type
Type o$ Activation
6hannels
The LR; that uni@uely identi$ies the ob?ect o$ that type.
We have to provide configuration information to /istener b9ect and also %lient b9ect .
)istener !on'iuration
%lic" here to download Time/istener.e+e.config .
!lient !on'iuration
%lic" here to download %lient.e+e.config .
Remoting .cti0ation
The .Net 2emoting framewor" supports -erver and %lient activation of 2emote b9ects. Before
an b9ect instance of a 2emotable type can be accessed, it must be created and initiali:ed by
#ctivation process. There are commonly two types of activation modes = -erver #ctivation and
%lient #ctivation mode. -erver activation is normally used when a 2emote ob9ects is not
re*uired to maintain any state between method calls. %lient #ctivated ob9ects are instantiated
from the client, and the client manages the lifetime of the 2emote b9ect by using a lease.based
system provided for that purpose.
ingle6all b9ects and ingleton b9ects belong to -erver #ctivation mode. !or -ingle%all
ob9ects the server will create a single ob9ect, e+ecute the method, and destroy the ob9ect again.
n the other hand with -ingleton mode only one ob9ect is created at all. -ingleton ob9ects can be
used to share information between multiple clients. The real distinction between %lient #ctivated
and -erver #ctivated ob9ect is that a server.activated ob9ect is not really created when a client
instantiates it. )nstead, it is created as needed.
Remoting C#annel
)n .Net 2emoting %hannels are used to transport messages to and from the 2emote b9ects.
%hannels are b9ects that responsible of handling the networ" protocols and seriali:ation
formats. )n .Net 2emoting channel can be implement either by calling the method
6hannelervices.Register6hannel or by using configuration file. %hannels should be registered
before ob9ects are registered.
When a channel is registered, it automatically starts listening for client re*uests at the specified
port. #t least one channel must be registered with the remoting framewor" before a 2emote
ob9ect can be called. There are two types of %hannels available in .Net 2emote !ramewor"=
8TT$ channel and T%$ channel. The 8TT$ channel transports messages to and from remote
ob9ects using the -#$ protocol. The T%$ channel uses a binary formatter to seriali:e all
messages to a binary stream and transport the stream to the target 32) using the T%$ protocol.
Remoting C#annel
Formatters are used for encoding and decoding the messages before they are
transported by the Channel in .Net Remoting Framework. The .Net Remoting
Framework supports two types of Formatters : Binary Formatter -
System.Runtime.Serialization.Formatters.Binary and !"# Formatter -
System.Runtime.Serialization.Formatters.Soap . The data in binary Formatter
has smaller si$e when compared to !"# Formatter. The !"# Formatter is an %&'
based cross platform te(t format ) so it can be human readable. The data in a !"#
Formatter larger si$e compared to Binary Formatter ) so it can therefore reduce
o*erall performance.
*o( to &'L in VB.NET
>M/ is a general purpose tag based language and very easy to transfer and store data across
applications. /i"e 8TM/ , >M/ is a subset of -7M/ . -tandard 7enerali:ed Mar"up /anguage.
>M/ is a platform independent language, so the information formatted in >M/ can be used in
any other platforms 0perating -ystems1. >M/ is a self describing language and it gives the data
as well as the rules to identify what information it contains.
>M/ files are made up of tags that contains data. 7enerally a start tag and end tag to hold the
data. !or e+ample, if you want to create an >M/ tag name G8eaderG , the start tag is li"e R
=eader S and the end tag is li"e R Q=eader S . We can fill our information between these tags.
R =eader S 8eader %ontent 8ere R Q=eader S
While creating an >M/ file , some important points have to remember =
N >M/ is case sensitive
e+= R =eader S is not same as R =eadeR S .
N Tags must be closed in the reverse order that they were opened
e+ = R $irstOtag SR secondOtag S ,ata here R QsecondOtag S R Q$irstOtag S
Sample F7) &ile
The .Net technology is widely supported >M/ file format. The .Net !ramewor" provides the
%lasses for read, write, and other operations in >M/ formatted files . These classes are stored in
the namespaces li"e -ystem.>ml, -ystem.>ml.-chema, -ystem.>ml.-eriali:ation,
-ystem.>ml.>$ath, -ystem.>ml.>sl etc. The ,ataset in #,.NET uses >M/ as its internal
storage format.
?ou can use any te+t editor to create an >M/ file . More over >M/ files are readable by humans
as well as computers. !rom the following lin"s you can see how to use >M/ in VB.NET.
*o( to create an &'L -le in VB.NET
>M/ is a platform independent language, so the information formatted in >M/ can be used in
any other platforms 0perating -ystems1. )f we create an >M/ file in one platform it can be used
in other platforms also.
!or creating a new >M/ file in VB.NET, we are using NmlTe-tDriter class . The class ta"es
!ileName and Encoding as argument. #lso we are here passing formating details . The following
source code creating an >M/ file product.+ml and add four rows in the file.
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im )riter s -e) 8ml'e*t+riter(.product.*ml."
System.'e*t.#ncodin$.F'FJ%
)riter.+riteStart(ocument('rue%
)riter.Formattin$ , Formattin$.Indented
)riter.Indentation , E
)riter.+riteStart#lement(.'able.%
create-ode(1" .Product 1." .1;;;." )riter%
create-ode(E" .Product E." .E;;;." )riter%
create-ode(H" .Product H." .H;;;." )riter%
create-ode(G" .Product G." .G;;;." )riter%
)riter.+rite#nd#lement(%
)riter.+rite#nd(ocument(%
)riter.Close(%
#nd Sub
Private Sub create-ode(ByVal pI( s Strin$" ByVal p-ame s Strin$" ByVal
pPrice s Strin$" ByVal )riter s 8ml'e*t+riter%
)riter.+riteStart#lement(.Product.%
)riter.+riteStart#lement(.Product_id.%
)riter.+riteStrin$(pI(%
)riter.+rite#nd#lement(%
)riter.+riteStart#lement(.Product_name.%
)riter.+riteStrin$(p-ame%
)riter.+rite#nd#lement(%
)riter.+riteStart#lement(.Product_price.%
)riter.+riteStrin$(pPrice%
)riter.+rite#nd#lement(%
)riter.+rite#nd#lement(%
#nd Sub
#nd Class
utput of the above source code =
*o( to open and read an &'L -le in VB.NET
>M/ is a self describing language and it gives the data as well as the rules to e+tract what the
data it contains. 2eading an >M/ file means that we are reading the information embedded in
>M/ tags in an >M/ file.
)n the previous program we create an >M/ file and named it as products.+ml. The following
program read that file and e+tract the contents inside the >M/ tag. We can read an >M/ file in
several ways depends on our re*uirement. This program read the content in Node wise . 8ere we
are using NmlDataDocument class to read the >M/ file . )n this program it search the Node R
2roduct S and its child Nodes and e+tract the data in child nodes.
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im *mldoc s -e) 8ml(ata(ocument(%
(im *mlnode s 8ml-ode1ist
(im i s Inte$er
(im str s Strin$
(im 3s s -e) FileStream(.products.*ml." File5ode.Open"
Fileccess.6ead%
*mldoc.1oad(3s%
*mlnode , *mldoc.9et#lementsBy'a$-ame(.Product.%
For i , ; 'o *mlnode.Count 2 1
*mlnode(i%.C4ild-odes.Item(;%.Inner'e*t.'rim(%
str , *mlnode(i%.C4ild-odes.Item(;%.Inner'e*t.'rim(% A . X . A
*mlnode(i%.C4ild-odes.Item(1%.Inner'e*t.'rim(% A . X . A
*mlnode(i%.C4ild-odes.Item(E%.Inner'e*t.'rim(%
5s$Bo*(str%
-e*t
#nd Sub
#nd Class
%lic" here to download the input file product.+ml
*o( to create an &'L -le in VB.NET using Dataset
>M/ is a tag based language, that means the document is made up of >M/ tags that contain
information. We can create an >M/ file in several ways.
)n the previous section we create an >M/ file using NmlTe-tDriter %lass. 8ere we are creating
an >M/ file $roduct.>M/ using an #,.NET ,ataset. !or that we have to manually create a
,atatable first and add the data of $roduct.>M/ in the ,atatable . Then add the ,atatable in a
,ataset . %all the method Write>ml of ,ataset and pass the file name $roduct.>M/ as argument.
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Imports System.(ata
Public Class Form1
(im dt s (ata'able
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im ds s -e) (ataSet
dt , -e) (ata'able(%
dt.Columns.dd(-e) (ataColumn(.Product_I(."
'ype.9et'ype(.System.IntHE.%%%
dt.Columns.dd(-e) (ataColumn(.Product_-ame."
'ype.9et'ype(.System.Strin$.%%%
dt.Columns.dd(-e) (ataColumn(.product_Price."
'ype.9et'ype(.System.IntHE.%%%
3ill6o)s(1" .product1." 1111%
3ill6o)s(E" .productE." EEEE%
3ill6o)s(H" .productH." HHHH%
3ill6o)s(G" .productG." GGGG%
ds.'ables.dd(dt%
ds.'ables(;%.'able-ame , .product.
ds.+rite8ml(.Product.*ml.%
5s$Bo*(.(one.%
#nd Sub
Private Sub 3ill6o)s(ByVal pI( s Inte$er" ByVal p-ame s Strin$" ByVal
pPrice s Inte$er%
(im dr s (ata6o)
dr , dt.-e)6o)(%
dr(.Product_I(.% , pI(
dr(.Product_-ame.% , p-ame
dr(.product_Price.% , pPrice
dt.6o)s.dd(dr%
#nd Sub
#nd Class
*o( to read an &'L -le in VB.NET using .D+.NET 3
Dataset
>M/ is a platform independent language, so the information formatted in >M/ can be use in
any other platforms 0perating -ystems1 . The .Net technology is widely supported >M/ file
format. The .Net !ramewor" provides the %lasses for read, write, and other operations in >M/
formatted files .
)n the previous section we already saw how to read an >M/ file through Node navigation . 8ere
we are going to read an >M/ file using an ,ata-et. 8ere ,ataset is using an NmlReader for read
the content of the file. /ocate the >M/ file using NmlReader and pass the >ml2eader as
argument of ,ataset.
%lic" here to download the input file product.+ml
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Imports System.(ata
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im *mlFile s 8ml6eader
*mlFile , 8ml6eader.Create(.Product.*ml." -e) 8ml6eaderSettin$s(%%
(im ds s -e) (ataSet
ds.6ead8ml(*mlFile%
(im i s Inte$er
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
5s$Bo*(ds.'ables(;%.6o)s(i%.Item(1%%
-e*t
#nd Sub
#nd Class
*o( to create an &'L -le !rom S%L in VB.NET
>M/ is a general purpose tag based language and very easy to transfer and store data across
applications. The .Net technology is widely supported >M/ file format. The .Net !ramewor"
provides the %lasses for read, write, and other operations in >M/ formatted files . Moreover the
,ataset in #,.NET uses >M/ format as its internal storage format.
There are several ways to create an >M/ file . )n the previous sections we already saw how to
create an >M/ file using >mlTe+tWriter and also created an >M/ file using manually created
,ataset. 8ere we are going to create an >M/ file from ,atabase. Ma"e an -P/ connection to
the ,atabase and e+ecute the s*l and store the data in a ,atset. %all ,ataset6s DriteNml./ method
and pass the file name as argument.
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im adapter s S:l(atadapter
(im ds s -e) (ataSet
(im s:l s Strin$
connetionStrin$ , .(ata Source,servernameOInitial
Catalo$,databsenameOFser I(,usernameOPass)ord,pass)ord.
connection , -e) S:lConnection(connetionStrin$%
s:l , .select P 3rom Product.
'ry
connection.Open(%
adapter , -e) S:l(atadapter(s:l" connection%
adapter.Fill(ds%
connection.Close(%
ds.+rite8ml(.Product.*ml.%
5s$Bo*(.(one.%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
?ou have to pass necessary database connection information to connection string.
*o( to searc# in an &'L -le
>M/ files are made up of tags that contains information. The .Net technology is widely
supported >M/ file format. #lso the ,ataset in #,.NET uses >M/ format as its internal
storage format.
The following source code shows how to search an item in an >M/ file using ,ataset . 8ere
,ataset using an >ml2eader for read the content of the file. /ocate the >M/ file using
>ml2eader and pass the >ml2eader as argument of ,ataset. By using the ,ataset , search the
product $roduct5 in the file $roduct.>M/ with the help of ,ataView.
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im *mlFile s 8ml6eader
*mlFile , 8ml6eader.Create(.Product.*ml." -e) 8ml6eaderSettin$s(%%
(im ds s -e) (ataSet
(im dv s (ataVie)
ds.6ead8ml(*mlFile%
dv , -e) (ataVie)(ds.'ables(;%%
dv.Sort , .Product_-ame.
(im inde* s Inte$er , dv.Find(.ProductE.%
I3 inde* , 21 '4en
5s$Bo*(.Item -ot Found.%
#lse
5s$Bo*(dv(inde*%(.Product_-ame.%.'oStrin$(% A . . A dv(inde*%
(.Product_Price.%.'oStrin$(%%
#nd I3
#nd Sub
%lic" here to download the input file product.+ml
*o( to -lter data in an &'L -le
>M/ is a platform independent language, so the information formatted in >M/ can be used in
any other platforms 0perating -ystems1. )f we create an >M/ file in one platform it can be used
in other platforms also. The .Net technology is widely supported >M/ file format. #lso the
,ataset in #,.NET uses >M/ format as its internal storage format.
8ere we are going to filter an >M/ file content and store the result in a newly created >M/ file.
We have an >M/ file $roduct.>M/ , and it has a field $roductE$rice. We are giving a search
criteria li"e the $roductE$rice LF 4DDD and store the result in a newly created >M/ file
2esult.>M/.
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im *mlFile s 8ml6eader
*mlFile , 8ml6eader.Create(.Product.*ml." -e) 8ml6eaderSettin$s(%%
(im ds s -e) (ataSet
(im dv s (ataVie)
ds.6ead8ml(*mlFile%
dv , -e) (ataVie)(ds.'ables(;%" .Product_price S , H;;;."
.Product_-ame." (ataVie)6o)State.Current6o)s%
dv.'o'able(%.+rite8ml(.6esult.*ml.%
5s$Bo*(.(one.%
#nd Sub
#nd Class
%lic" here to download the input file product.+ml
*o( to insert data !rom xml to data$ase
>M/ is a general purpose tag based language and very easy to transfer and store data across
applications. The .Net technology is widely supported >M/ file format. The .Net !ramewor"
provides the %lasses for read, write, and other operations in >M/ formatted files . Moreover the
,ataset in #,.NET uses >M/ format as its internal storage format.
8ere we are going to insert the values of an >M/ file to a ,atabase Table using -P/ insert
command. 8ere the ,ataset using an >ml2eader for read the content of the >M/ file .
$roduct.>M/ . /ocate the >M/ file using >ml2eader and pass the >ml2eader as argument of
,ataset. #lso establish a connection to the ,atabase using a connectionstring . #fter getting the
data from >M/ file to the ,ataset , we can loop through the dataset values and use insert
command to add the values to the $roduct table in the ,atabse.
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connetionStrin$ s Strin$
(im connection s S:lConnection
(im command s S:lCommand
(im adpter s -e) S:l(atadapter
(im ds s -e) (ataSet
(im *mlFile s 8ml6eader
(im s:l s Strin$
(im product_I( s Inte$er
(im Product_-ame s Strin$
(im product_Price s (ouble
connetionStrin$ , .(ata Source,servernameOInitial
Catalo$,databsenameOFser I(,usernameOPass)ord,pass)ord.
connection , -e) S:lConnection(connetionStrin$%
*mlFile , 8ml6eader.Create(.Product.*ml." -e) 8ml6eaderSettin$s(%%
ds.6ead8ml(*mlFile%
(im i s Inte$er
connection.Open(%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
product_I( , Convert.'oIntHE(ds.'ables(;%.6o)s(i%.Item(;%%
Product_-ame , ds.'ables(;%.6o)s(i%.Item(1%
product_Price , Convert.'o(ouble(ds.'ables(;%.6o)s(i%.Item(E%%
s:l , .insert into Product values(. A product_I( A ."D. A
Product_-ame A .D". A product_Price A .%.
command , -e) S:lCommand(s:l" connection%
adpter.InsertCommand , command
adpter.InsertCommand.#*ecute-onCuery(%
-e*t
connection.Close(%
#nd Sub
#nd Class
?ou have to pass necessary database connection information to connection string.
%lic" here to download the input file product.+ml
*o( to create an Excel -le !rom &'L
>M/ is a platform independent language, so the information formatted in >M/ can be used in
any other platforms 0perating -ystems1. >M/ is a self describing language and it gives the data
as well as the rules to identify what the data it contains.
8ere we are going to read from an >M/ file content and write the same content to an E+cel file.
3sing an NmlReader for read the >M/ file to the ,ataset . /oop through the ,ataset and add the
content to the E+cel file . !or create an e+cel file you have to add reference of E+cel library to
you pro9ect .
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Imports System.(ata
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
(im ds s -e) (ataSet
(im *mlFile s 8ml6eader
(im i" ! s Inte$er
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
*mlFile , 8ml6eader.Create(.Product.*ml." -e) 8ml6eaderSettin$s(%%
ds.6ead8ml(*mlFile%
For i , ; 'o ds.'ables(;%.6o)s.Count 2 1
For ! , ; 'o ds.'ables(;%.Columns.Count 2 1
*l+orkS4eet.Cells(i N 1" ! N 1% , _
ds.'ables(;%.6o)s(i%.Item(!%
-e*t
-e*t
*l+orkS4eet.Saves(.*mlEe*cel.*ls*.%
*l+orkBook.Close(%
*lpp.Cuit(%
releaseOb!ect(*lpp%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*l+orkS4eet%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
%lic" here to download the input file product.+ml
*o( to create an &'L -le !rom Excel
>M/ is a general purpose tag based language and very easy to transfer and store data across
applications. The .Net !ramewor" provides the %lasses for read, write, and other operations in
>M/ formatted files .
The following program shows how to create an >M/ file from an E+cel file content . 8ere we
are using an 5leDb6onnection to read the e+cel file and store the content to a ,ataset . %all the
method DriteNml of ,atset to write to the >M/ file.
Do$nload Source !ode
Print Source !ode
Imports System.(ata
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
'ry
(im 5yConnection s System.(ata.Ole(b.Ole(bConnection
(im ds s System.(ata.(ataSet
(im 5yCommand s System.(ata.Ole(b.Ole(b(atadapter
5yConnection , -e) System.(ata.Ole(b.Ole(bConnection _
(.provider,5icroso3t.Met.O1#(B.G.;O(ata
Source,D*lE*ml.*lsDO#*tended Properties,#*cel J.;O.%
5yCommand , -e) System.(ata.Ole(b.Ole(b(atadapter _
(.select P 3rom ?S4eet1Q@." 5yConnection%
5yCommand.'able5appin$s.dd(.'able." .Product.%
ds , -e) System.(ata.(ataSet
5yCommand.Fill(ds%
5yConnection.Close(%
ds.+rite8ml(.Product.*ml.%
Catc4 e* s #*ception
5s$Bo*(e*.'oStrin$%
#nd 'ry
#nd Sub
#nd Class
%lic" here to download the input e+cel file +l5+ml.+ls
*o( to xml to Data4ridVie(
>M/ is a platform independent language, so the information formatted in >M/ file can be use in
any other platforms . The .Net technology is widely supported >M/ file format. The following
source code shows , how to load data in a ,ata7ridView from an >M/ file . 8ere the ,ataset
using an >ml2eader for read the content of the >M/ file . $roduct.>M/ . /ocate the >M/ file
using >ml2eader and pass the >ml2eader as argument of ,ataset. When the ,ataset retrieves
the data, it passes as ,ata-ource to Data<ridVie9 .
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Imports System.(ata
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im *mlFile s 8ml6eader
*mlFile , 8ml6eader.Create(.Product.*ml." -e) 8ml6eaderSettin$s(%%
(im ds s -e) (ataSet
ds.6ead8ml(*mlFile%
(ata9ridVie)1.(ataSource , ds.'ables(;%
#nd Sub
#nd Class
%lic" here to download the input file product.+ml
*o( to create a Tree0Vie( !rom &'L
>M/ is a self describing language and it gives the data as well as the rules to e+tract what the
data it contains. 2eading an >M/ file means that we are reading the data embedded in tags in an
>M/ file.
)n the previous e+ample we already saw how to read an >M/ file Node wise. 8ere we are
reading >M/ file as Node and pass the Nodes data to TreeView.
Do$nload Source !ode
Print Source !ode
Imports System.8ml
Imports System.io
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im *mldoc s -e) 8ml(ata(ocument(%
(im *mlnode s 8ml-ode
(im 3s s -e) FileStream(.tree.*ml." File5ode.Open" Fileccess.6ead%
*mldoc.1oad(3s%
*mlnode , *mldoc.C4ild-odes(1%
'reeVie)1.-odes.Clear(%
'reeVie)1.-odes.dd(-e) 'ree-ode(*mldoc.(ocument#lement.-ame%%
(im t-ode s 'ree-ode
t-ode , 'reeVie)1.-odes(;%
dd-ode(*mlnode" t-ode%
#nd Sub
Private Sub dd-ode(ByVal in8ml-ode s 8ml-ode" ByVal in'ree-ode s
'ree-ode%
(im *-ode s 8ml-ode
(im t-ode s 'ree-ode
(im node1ist s 8ml-ode1ist
(im i s Inte$er
I3 in8ml-ode.&asC4ild-odes '4en
node1ist , in8ml-ode.C4ild-odes
For i , ; 'o node1ist.Count 2 1
*-ode , in8ml-ode.C4ild-odes(i%
in'ree-ode.-odes.dd(-e) 'ree-ode(*-ode.-ame%%
t-ode , in'ree-ode.-odes(i%
dd-ode(*-ode" t-ode%
-e*t
#lse
in'ree-ode.'e*t , in8ml-ode.Inner'e*t.'oStrin$
#nd I3
#nd Sub
#nd Class
%lic" here to download the input file tree.+ml
*o( to create Crystal Reports !rom &'L
>M/ is a self describing language and it gives the data as well as the rules to identify what the
data it contains. The .Net !ramewor" provides the %lasses for read, write, and other operations in
>M/ formatted files . We can use >M/ as a ,ata -ource to %rystal 2eports li"e a ,atabase .
%lic" here to see, 8ow to create %rystal 2eports from +ml .
*o( to seriali5ation in xml
>M/ -eriali:ation is the process of seriali:ing a .Net b9ect to the form of >M/ or from an
>M/ to .Net b9ect. The primary purpose of >M/ seriali:ation in the .NET !ramewor" is to
enable the conversion of >M/ documents and streams to common language runtime ob9ects and
vice versa. This is the process of converting an ob9ect into a form that can be readily transported.
,uring >M/ seriali:ation, only the public properties and fields of an ob9ect are seriali:ed. The
following lin"s gives you more details about >M/ -eriali:ation and ,e.seriali:ation.
8ow to seriali:e a .Net b9ect to >M/
8ow to de.seriali:e >M/ to .Net b9ect
*o( to seriali5e a .Net +$1ect to &'L
-eriali:ation of >M/ to common language runtime ob9ects enables one to convert >M/
documents into a form where they are easier to process using conventional programming
languages. The .Net technology is widely supported >M/ file format. The .Net !ramewor"
provides the %lasses for read, write, and other operations in >M/ formatted files .
The following program shows how to seriali:e a ,ataset to an >M/ dis" file . 8ere we are using
>ml-eriali:er class for seriali:e the ,ataset b9ect.
Do$nload Source !ode
Print Source !ode
Public Class Form1
(im dt s (ata'able
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im ds s -e) (ataSet
dt , -e) (ata'able(%
dt.Columns.dd(-e) (ataColumn(.Product_I(."
'ype.9et'ype(.System.IntHE.%%%
dt.Columns.dd(-e) (ataColumn(.Product_-ame."
'ype.9et'ype(.System.Strin$.%%%
dt.Columns.dd(-e) (ataColumn(.product_Price."
'ype.9et'ype(.System.IntHE.%%%
3ill6o)s(1" .product1." ====%
3ill6o)s(E" .productE." EEEE%
3ill6o)s(H" .productH." HHHH%
3ill6o)s(G" .productG." GGGG%
ds.'ables.dd(dt%
ds.'ables(;%.'able-ame , .product.
(im serial+riter s Stream+riter
serial+riter , -e) Stream+riter(.serial851.*ml.%
(im *ml+riter s -e) 8mlSeriali<er(ds.9et'ype(%%
*ml+riter.Seriali<e(serial+riter" ds%
serial+riter.Close(%
ds.Clear(%
#nd Sub
Private Sub 3ill6o)s(ByVal pI( s Inte$er" ByVal p-ame s Strin$" ByVal
pPrice s Inte$er%
(im dr s (ata6o)
dr , dt.-e)6o)(%
dr(.Product_I(.% , pI(
dr(.Product_-ame.% , p-ame
dr(.product_Price.% , pPrice
dt.6o)s.dd(dr%
#nd Sub
#nd Class
%lic" here to download serial>M/.+ml
*o( to de3seriali5e !rom an &'L -le to .Net +$1ect
>M/ is a general purpose tag based language and very easy to transfer and store data across
applications. >M/ -eriali:ation is the process of seriali:ing a .Net b9ect to the form of >M/
file or from an >M/ to .Net b9ect.
,uring >M/ seriali:ation, only the public properties and fields of an ob9ect are seriali:ed. The
following source code shows how to de.seriali:e the ,ata-et as it is streamed from an >M/ file
bac" into memory.
Do$nload Source !ode
Print Source !ode
Imports System.8ml.Seriali<ation
Imports System.io
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im ds s -e) (ataSet
(im *mlSeriali<er s 8mlSeriali<er , -e) 8mlSeriali<er(ds.9et'ype%
(im readStream s FileStream , -e) FileStream(.serial851.*ml."
File5ode.Open%
ds , C'ype(*mlSeriali<er.(eseriali<e(readStream%" (ataSet%
readStream.Close(%
(ata9ridVie)1.(ataSource , ds.'ables(;%
#nd Sub
#nd Class
VB.NET Data4ridVie( $inding 3 S2l Ser0er
?ou can e+tend the ,ata7ridView control in a number of ways to build custom behaviors into
your applications. The ,ata7ridView can display data in Bound mode, unbound mode and
Virtual mode . Bound mode is suitable for managing data using automatic interaction with the
data store. ne very common use of the ,ata7ridView control is binding to a table in a database.
3nbound mode is suitable for displaying relatively small amounts of data that you manage
programmatically. Virtual mode gives you a higher degree of control by allowing you to wait
until a cell is actually being displayed to provide the value it will contain.
The following vb.net program shows how to bind a -P/ -erver dataset in a ,ata7ridView.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connectionStrin$ s Strin$ , .(ata Source,.OInitial
Catalo$,pubsOInte$rated Security,'rue.
(im s:l s Strin$ , .S#1#C' P F6O5 ut4ors.
(im connection s -e) S:lConnection(connectionStrin$%
(im dataadapter s -e) S:l(atadapter(s:l" connection%
(im ds s -e) (ataSet(%
connection.Open(%
dataadapter.Fill(ds" .ut4ors_table.%
connection.Close(%
(ata9ridVie)1.(ataSource , ds
(ata9ridVie)1.(ata5ember , .ut4ors_table.
#nd Sub
#nd Class
Data4ridVie( $inding 3 +LEDB in VB.NET
The ,ata7ridView can display data in Bound mode and unbound mode and Virtual mode. The
easiest way to get started using the ,ata7ridView control is to use it in basic data binding
scenarios. The ,ata7ridView control can display rows of data from a data source. When you
specify a data source for the ,ata7ridView, by default it will construct columns for you
automatically. This will be created based on the data types in the data source.
The following vb.net program shows how to bind an /E,B dataset in a ,ata7ridView.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.Ole(b
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connectionStrin$ s Strin$ ,
.Provider,5icroso3t.Met.O1#(B.G.;O(ata Source,.Rour .mdb pat4.O.
(im s:l s Strin$ , .S#1#C' P F6O5 ut4ors.
(im connection s -e) Ole(bConnection(connectionStrin$%
(im dataadapter s -e) Ole(b(atadapter(s:l" connection%
(im ds s -e) (ataSet(%
connection.Open(%
dataadapter.Fill(ds" .ut4ors_table.%
connection.Close(%
(ata9ridVie)1.(ataSource , ds
(ata9ridVie)1.(ata5ember , .ut4ors_table.
#nd Sub
#nd Class
Data4ridVie( Sorting6Filtering in VB.NET
The ,ata7ridView control provides a customi:able table for displaying data. ?ou can e+tend the
,ata7ridView control in a number of ways to build custom behaviors into your applications. #
,ataView provides a means to filter and sort data within a ,ataTable. The following vb.net
program shows how to filter and sort a ,ata7ridView by using a ,ataView b9ect.
,im dv #s ,ataView
dv F New ,ataView0ds.Tables0D1, G$rice L AJG, G$rice ,escG, ,ataView2ow-tate.%urrent2ows1
,ata7ridViewA.,ata-ource F dv
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connectionStrin$ s Strin$ , .(ata Source,.OInitial
Catalo$,pubsOInte$rated Security,'rue.
(im s:l s Strin$ , .S#1#C' P F6O5 'itles.
(im connection s -e) S:lConnection(connectionStrin$%
(im dataadapter s -e) S:l(atadapter(s:l" connection%
(im ds s -e) (ataSet(%
connection.Open(%
dataadapter.Fill(ds" .'itles_table.%
connection.Close(%
(im dv s (ataVie)
dv , -e) (ataVie)(ds.'ables(;%" .Price S 1=." .Price (esc."
(ataVie)6o)State.Current6o)s%
(ata9ridVie)1.(ataSource , dv
#nd Sub
#nd Class
Data4ridVie( adding ro(s and columns in VB.NET
The ,ata7ridView control is designed to be a complete solution for displaying tabular data with
Windows !orms. The ,ata7ridView control is highly configurable and e+tensible, and it
provides many properties, methods, and events to customi:e its appearance and behavior. The
,ata7ridView control is used to display data from a variety of e+ternal data sources.
#lternatively, you can add rows and columns to the control and manually populate it with data.
The following vb.net source code shows how to manually create %olumns and 2ows in a
,ata7ridView.
,ata7ridViewA.%olumns0)nde+1.Name F G%olumn NameG
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(ata9ridVie)1.ColumnCount , H
(ata9ridVie)1.Columns(;%.-ame , .Product I(.
(ata9ridVie)1.Columns(1%.-ame , .Product -ame.
(ata9ridVie)1.Columns(E%.-ame , .Product_Price.
(im ro) s Strin$(% , -e) Strin$(% U.1." .Product 1." .1;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.E." .Product E." .E;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.H." .Product H." .H;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.G." .Product G." .G;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
#nd Sub
#nd Class
Data4ridVie( #iding ro(s and columns in VB.NET
The ,ata7ridView control provides a customi:able table for displaying data. )t gives you
number of properties, methods and events to customi:e its appearance and behavior. ,isplaying
data in a tabular format is a tas" you are li"ely to perform fre*uently. The ,ata7ridView control
is designed to be a complete solution for displaying tabular data with Windows !orms . The
following vb.net source code manually creates a ,ata7ridView columns and rows and hide the
second column and second row.
,ata7ridViewA.2ows0)nde+1.Visible F !alse
,ata7ridViewA.%olumns0)nde+1.Visible F !alse
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(ata9ridVie)1.ColumnCount , H
(ata9ridVie)1.Columns(;%.-ame , .Product I(.
(ata9ridVie)1.Columns(1%.-ame , .Product -ame.
(ata9ridVie)1.Columns(E%.-ame , .Product_Price.
(im ro) s Strin$(% , -e) Strin$(% U.1." .Product 1." .1;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.E." .Product E." .E;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.H." .Product H." .H;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.G." .Product G." .G;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
(ata9ridVie)1.6o)s(1%.Visible , False
#nd Sub
#nd Class
Data4ridVie( Read+nly ro(s and columns in
VB.NET
The ,ata7ridView control can display rows of data from a data source. ?ou can e+tend the
,ata7ridView control in a number of ways to build custom behaviors into your applications. The
2eadnly property indicates whether the data displayed by the cell can be edited or not. ?ou can
set 2eadnly $roperty in three levels. ?ou can ma"e entire data7ridView as 2eadnly.
data7ridViewA.2eadnly F true
?ou can ma"e entire row as 2eadnly
data7ridViewA.2ows0inde+1.2eadnly F trueW
?ou can ma"e entire %olumn as 2eadnly
data7ridViewA.%olumns0inde+1.2eadnly F trueW
The following vb.net source code shows how to ma"e a row as 2eadonly in a ,ata7ridView.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(ata9ridVie)1.ColumnCount , H
(ata9ridVie)1.Columns(;%.-ame , .Product I(.
(ata9ridVie)1.Columns(1%.-ame , .Product -ame.
(ata9ridVie)1.Columns(E%.-ame , .Product_Price.
(im ro) s Strin$(% , -e) Strin$(% U.1." .Product 1." .1;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.E." .Product E." .E;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.H." .Product H." .H;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.G." .Product G." .G;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
(ata9ridVie)1.6o)s(1%.6eadOnly , 'rue
#nd Sub
#nd Class
.dding Button to Data4ridVie( in VB.NET
The ,ata7ridView control is highly configurable and e+tensible, and it provides many
properties, methods, and events to customi:e its appearance and behavior. The ,ata7ridView
control provides Te+tBo+, %hec"Bo+, )mage, Button, %omboBo+ and /in" columns with the
corresponding cell types. With the ,ata7ridViewButton%olumn, you can display a column of
cells that contain buttons.?ou can respond to user clic"s in button cells by handling the
,ata7ridView.%ell%lic" event.
The following vb.net program shows how to add a Button in %ell of a ,ata7ridView control.
#lso it showing in the ,ata7ridView.%ell%lic" event which button the user clic"ed.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(ata9ridVie)1.ColumnCount , H
(ata9ridVie)1.Columns(;%.-ame , .Product I(.
(ata9ridVie)1.Columns(1%.-ame , .Product -ame.
(ata9ridVie)1.Columns(E%.-ame , .Product_Price.
(im ro) s Strin$(% , -e) Strin$(% U.1." .Product 1." .1;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.E." .Product E." .E;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.H." .Product H." .H;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.G." .Product G." .G;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
(im btn s -e) (ata9ridVie)ButtonColumn(%
(ata9ridVie)1.Columns.dd(btn%
btn.&eader'e*t , .Click (ata.
btn.'e*t , .Click &ere.
btn.-ame , .btn.
btn.FseColumn'e*tForButtonValue , 'rue
#nd Sub
Private Sub (ata9ridVie)1_CellClick(ByVal sender s System.Ob!ect" ByVal e
s System.+indo)s.Forms.(ata9ridVie)Cell#ventr$s% &andles
(ata9ridVie)1.CellClick
I3 e.ColumnInde* , H '4en
5s$Bo*((.6o) / . N e.6o)Inde*.'oStrin$ A . Col / .% N
e.ColumnInde*.'oStrin$%
#nd I3
#nd Sub
#nd Class
.dding C#ec)Box to Data4ridVie( in VB.NET
The ,ata7ridView control uses several column types to display its information and enable users
to modify or add information. The ,ata7ridView control provides Te+tBo+, %hec"Bo+, )mage,
Button, %omboBo+ and /in" columns with the corresponding cell types.
The following vb.net program shows how to add a %hec"Bo+ in %ell of a ,ata7ridView control
and set the third row chec"bo+ value as true. )f you want to respond immediately when users
clic" a chec" bo+ cell, you can handle the %ell%lic" event, but this event occurs before the cell
value is updated.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(ata9ridVie)1.ColumnCount , H
(ata9ridVie)1.Columns(;%.-ame , .Product I(.
(ata9ridVie)1.Columns(1%.-ame , .Product -ame.
(ata9ridVie)1.Columns(E%.-ame , .Product_Price.
(im ro) s Strin$(% , -e) Strin$(% U.1." .Product 1." .1;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.E." .Product E." .E;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.H." .Product H." .H;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.G." .Product G." .G;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
(im c4k s -e) (ata9ridVie)C4eckBo*Column(%
(ata9ridVie)1.Columns.dd(c4k%
c4k.&eader'e*t , .C4eck (ata.
c4k.-ame , .c4k.
(ata9ridVie)1.6o)s(E%.Cells(H%.Value , 'rue
#nd Sub
#nd Class
.dding Com$oBox to Data4ridVie( in VB.NET
The ,ata7ridView control provides Te+tBo+, %hec"Bo+, )mage, Button, %omboBo+ and /in"
columns with the corresponding cell types. ?ou can populate the drop down list used for all cells
the same way you would populate a %omboBo+ drop down list, either manually through the
collection returned by the )tems property, or by binding it to a data source through the
,ata-ource, ,isplayMember, and ValueMember properties.
The following vb.net program shows how to add a %omboBo+ in %ell of a ,ata7ridView
control.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(ata9ridVie)1.ColumnCount , H
(ata9ridVie)1.Columns(;%.-ame , .Product I(.
(ata9ridVie)1.Columns(1%.-ame , .Product -ame.
(ata9ridVie)1.Columns(E%.-ame , .Product_Price.
(im ro) s Strin$(% , -e) Strin$(% U.1." .Product 1." .1;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.E." .Product E." .E;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.H." .Product H." .H;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.G." .Product G." .G;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
(im cmb s -e) (ata9ridVie)ComboBo*Column(%
cmb.&eader'e*t , .Select (ata.
cmb.-ame , .cmb.
cmb.5a*(rop(o)nItems , G
cmb.Items.dd(.'rue.%
cmb.Items.dd(.False.%
(ata9ridVie)1.Columns.dd(cmb%
#nd Sub
#nd Class
.dding Image to Data4ridVie( in VB.NET
The ,ata7ridView control and its related classes are designed to be a fle+ible, e+tensible system
for displaying and editing tabular data. We can add an )mage control in a column of
,ata7ridView. This column type e+poses )mage and )mage/ayout properties in addition to the
usual base class properties. -etting the columns )mage property results in that image being
displayed by default for all the cells in that column. $opulating an image column manually is
useful when you want to provide the functionality of a ,ata7ridViewButton%olumn, but with a
customi:ed appearance.
The following vb.net program shows how to add a )mage in column of a ,ata7ridView control.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(ata9ridVie)1.ColumnCount , H
(ata9ridVie)1.Columns(;%.-ame , .Product I(.
(ata9ridVie)1.Columns(1%.-ame , .Product -ame.
(ata9ridVie)1.Columns(E%.-ame , .Product_Price.
(im ro) s Strin$(% , -e) Strin$(% U.1." .Product 1." .1;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.E." .Product E." .E;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.H." .Product H." .H;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.G." .Product G." .G;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
(im im$ s -e) (ata9ridVie)Ima$eColumn(%
(im inIm$ s Ima$e , Ima$e.FromFile(.Ima$e Pat4.%
im$.Ima$e , inIm$
(ata9ridVie)1.Columns.dd(im$%
im$.&eader'e*t , .Ima$e.
im$.-ame , .im$.
#nd Sub
#nd Class
.dding Vie(Lin) to Data4ridVie( in VB.NET
The ,ata7ridView control provides Te+tBo+, %hec"Bo+, )mage, Button, %omboBo+ and /in"
columns with the corresponding cell types. We can add hyperlin" in the column of a
,ata7ridView , the column type contains cells of type ,ata7ridView/in"%ell and renders the
te+t in the cell to loo" li"e a hyperlin". /in" columns are not generated automatically when data
binding a ,ata7ridView control. To use lin" columns, you must create them manually and add
them to the collection returned by the %olumns property.
The following vb.net program shows how to add a hyperlin" in a column of ,ata7ridView
control.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(ata9ridVie)1.ColumnCount , H
(ata9ridVie)1.Columns(;%.-ame , .Product I(.
(ata9ridVie)1.Columns(1%.-ame , .Product -ame.
(ata9ridVie)1.Columns(E%.-ame , .Product_Price.
(im ro) s Strin$(% , -e) Strin$(% U.1." .Product 1." .1;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.E." .Product E." .E;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.H." .Product H." .H;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
ro) , -e) Strin$(% U.G." .Product G." .G;;;.V
(ata9ridVie)1.6o)s.dd(ro)%
(im lnk s -e) (ata9ridVie)1inkColumn(%
(ata9ridVie)1.Columns.dd(lnk%
lnk.&eader'e*t , .1ink (ata.
lnk.-ame , .4ttp/BBvb.net2in3ormations.com.
lnk.'e*t , .4ttp/BBvb.net2in3ormations.com.
lnk.FseColumn'e*tFor1inkValue , 'rue
#nd Sub
#nd Class
*o( to aging in Data4ridVie(
The ,ata7ridView class allows customi:ation of cells, rows, columns, and borders through the
use of its properties . )f a ,ata7ridView has lot of rows then we can implement paging
functionalities to the ,ata7ridView control. While we implement paging we should "now the
boundaries of the pages to enable the paging in the ,atagridView.
The following vb.net program provides a way to programmatically implement paging in a
Windows ,atagrid View control. 8ere the ,ata7ridView rows fi+ed as five rows and other two
buttons are there for implementing paging functionalities.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
(im pa$in$dapter s S:l(atadapter
(im pa$in$(S s (ataSet
(im scrollVal s Inte$er
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connectionStrin$ s Strin$ , .(ata Source,.OInitial
Catalo$,pubsOInte$rated Security,'rue.
(im s:l s Strin$ , .S#1#C' P F6O5 aut4ors.
(im connection s -e) S:lConnection(connectionStrin$%
pa$in$dapter , -e) S:l(atadapter(s:l" connection%
pa$in$(S , -e) (ataSet(%
connection.Open(%
pa$in$dapter.Fill(pa$in$(S" scrollVal" I" .aut4ors_table.%
connection.Close(%
(ata9ridVie)1.(ataSource , pa$in$(S
(ata9ridVie)1.(ata5ember , .aut4ors_table.
#nd Sub
Private Sub buttonE_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles buttonE.Click
scrollVal , scrollVal 2 I
I3 scrollVal W, ; '4en
scrollVal , ;
#nd I3
pa$in$(S.Clear(%
pa$in$dapter.Fill(pa$in$(S" scrollVal" I" .aut4ors_table.%
#nd Sub
Private Sub buttonH_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles buttonH.Click
scrollVal , scrollVal N I
I3 scrollVal S EH '4en
scrollVal , 1J
#nd I3
pa$in$(S.Clear(%
pa$in$dapter.Fill(pa$in$(S" scrollVal" I" .aut4ors_table.%
#nd Sub
#nd Class
*o( to Formatting in Data4ridVie(
The ,ata7ridView control is highly configurable and e+tensible, and it provides many
properties, methods, and events to customi:e its appearance and behavior. ?ou can e+tend the
,ata7ridView control in a number of ways to build custom behaviors into your applications.
The ,ata7ridView control ma"es it easy to define the basic appearance of cells and the display
formatting of cell values. Typically, however, multiple cells will share particular style
characteristics. ?ou can define appearance and formatting styles for individual cells, for cells in
specific columns and rows, or for all cells in the control by setting the properties of the
,ata7ridView%ell-tyle ob9ects accessed through various ,ata7ridView control properties.
The following vb.net program shows how to implement different ways of cell formatting in a
,ata7ridView control.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connectionStrin$ s Strin$ , .(ata Source,.OInitial
Catalo$,pubsOInte$rated Security,'rue.
(im s:l s Strin$ , .S#1#C' P F6O5 ut4ors.
(im connection s -e) S:lConnection(connectionStrin$%
(im dataadapter s -e) S:l(atadapter(s:l" connection%
(im ds s -e) (ataSet(%
connection.Open(%
dataadapter.Fill(ds" .ut4ors_table.%
connection.Close(%
(ata9ridVie)1.(ataSource , ds
(ata9ridVie)1.(ata5ember , .ut4ors_table.
(ata9ridVie)1.9ridColor , Color.6ed
(ata9ridVie)1.CellBorderStyle , (ata9ridVie)CellBorderStyle.-one
(ata9ridVie)1.Back$roundColor , Color.1i$4t9ray
(ata9ridVie)1.(e3aultCellStyle.SelectionBackColor , Color.6ed
(ata9ridVie)1.(e3aultCellStyle.SelectionForeColor , Color.Rello)
(ata9ridVie)1.(e3aultCellStyle.+rap5ode , (ata9ridVie)'riState.?'rue@
(ata9ridVie)1.Selection5ode , (ata9ridVie)Selection5ode.Full6o)Select
(ata9ridVie)1.llo)Fser'o6esi<eColumns , False
(ata9ridVie)1.6o)s(e3aultCellStyle.BackColor , Color.Bis:ue
(ata9ridVie)1.lternatin$6o)s(e3aultCellStyle.BackColor , Color.Bei$e
#nd Sub
#nd Class
*o( to Data4ridVie( Template
There are situations that you want greater control over the appearance of ,ata7ridView rows
than what is provided by the various ,ata7ridView cell style properties. The row template gives
you greater control over the appearance and behavior of rows than the 2ows,efault%ell-tyle
property provides. With the row template, you can set any ,ata7ridView2ow properties,
including ,efault%ell-tyle. When displaying e+ternal data, however, the rows are generated
automatically, but they are based on the row template, which you can set to an instance of your
custom row type.
The following vb.net code e+ample illustrates how to use the row template to specify an initial
row height and a minimum row height and Bac"%olor.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im ro) s (ata9ridVie)6o) , 5e.(ata9ridVie)1.6o)'emplate
ro).(e3aultCellStyle.BackColor , Color.Bis:ue
ro).&ei$4t , HI
ro).5inimum&ei$4t , E;
(im connectionStrin$ s Strin$ , .(ata Source,.OInitial
Catalo$,pubsOInte$rated Security,'rue.
(im s:l s Strin$ , .S#1#C' P F6O5 ut4ors.
(im connection s -e) S:lConnection(connectionStrin$%
(im dataadapter s -e) S:l(atadapter(s:l" connection%
(im ds s -e) (ataSet(%
connection.Open(%
dataadapter.Fill(ds" .ut4ors_table.%
connection.Close(%
(ata9ridVie)1.(ataSource , ds
(ata9ridVie)1.(ata5ember , .ut4ors_table.
#nd Sub
#nd Class
*o( to Data4ridVie( rinting
The ,ata7ridView control provides a customi:able table for displaying data. )t gives you
number of properties, methods and events to customi:e its appearance and behavior.
3nfortunately the ,ata7ridView doesn6t have a built in printing functionality . -o here we do a
tric"y way to print the content of ,ata7ridView . 8ere we add a $rint,ocument ob9ect to the
pro9ect and handle the $rint$age event which is called every time a new page is to be printed.
8ere in the $rint$age event we create a Bitmap b9ect and draw the ,ata7ridView to the
Bitmap b9ect.
)n order to run this vb.net pro9ect you have to drag two buttons ,one for load data and one for
print command, and drag a $rint,ocument control on your form . The following picture shows
how to drag $rint,ocument b9ect to your pro9ect.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connectionStrin$ s Strin$ , .(ata Source,.OInitial
Catalo$,pubsOInte$rated Security,'rue.
(im s:l s Strin$ , .S#1#C' P F6O5 ut4ors.
(im connection s -e) S:lConnection(connectionStrin$%
(im dataadapter s -e) S:l(atadapter(s:l" connection%
(im ds s -e) (ataSet(%
connection.Open(%
dataadapter.Fill(ds" .ut4ors_table.%
connection.Close(%
(ata9ridVie)1.(ataSource , ds
(ata9ridVie)1.(ata5ember , .ut4ors_table.
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles ButtonE.Click
Print(ocument1.Print(%
#nd Sub
Private Sub Print(ocument1_PrintPa$e(ByVal sender s System.Ob!ect" ByVal
e s System.(ra)in$.Printin$.PrintPa$e#ventr$s% &andles
Print(ocument1.PrintPa$e
(im bm s -e) Bitmap(5e.(ata9ridVie)1.+idt4" 5e.(ata9ridVie)1.&ei$4t%
(ata9ridVie)1.(ra)'oBitmap(bm" -e) 6ectan$le(;" ;"
5e.(ata9ridVie)1.+idt4" 5e.(ata9ridVie)1.&ei$4t%%
e.9rap4ics.(ra)Ima$e(bm" ;" ;%
#nd Sub
#nd Class
*o( to Export datagrid0ie( to Excel
The ,ata7ridView control provides a customi:able table for displaying data. ,isplaying data in
a tabular format is a tas" you are li"ely to perform fre*uently. The ,ata7ridView control is
highly configurable and e+tensible, and it provides many properties, methods, and events to
customi:e its appearance and behavior.
The following vb.net source code shows how to E+port the content of a datagridview to an E+cel
file.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Imports #*cel , 5icroso3t.O33ice.Interop.#*cel
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im connectionStrin$ s Strin$ , .(ata Source,.OInitial
Catalo$,pubsOInte$rated Security,'rue.
(im s:l s Strin$ , .S#1#C' P F6O5 ut4ors.
(im connection s -e) S:lConnection(connectionStrin$%
(im dataadapter s -e) S:l(atadapter(s:l" connection%
(im ds s -e) (ataSet(%
connection.Open(%
dataadapter.Fill(ds" .ut4ors_table.%
connection.Close(%
(ata9ridVie)1.(ataSource , ds
(ata9ridVie)1.(ata5ember , .ut4ors_table.
#nd Sub
Private Sub ButtonE_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles ButtonE.Click
(im *lpp s #*cel.pplication
(im *l+orkBook s #*cel.+orkbook
(im *l+orkS4eet s #*cel.+orks4eet
(im misValue s Ob!ect , System.6e3lection.5issin$.Value
(im i s Int1>" ! s Int1>
*lpp , -e) #*cel.pplicationClass
*l+orkBook , *lpp.+orkbooks.dd(misValue%
*l+orkS4eet , *l+orkBook.S4eets(.s4eet1.%
For i , ; 'o (ata9ridVie)1.6o)Count 2 E
For ! , ; 'o (ata9ridVie)1.ColumnCount 2 1
*l+orkS4eet.Cells(i N 1" ! N 1% , (ata9ridVie)1(!"
i%.Value.'oStrin$(%
-e*t
-e*t
*l+orkBook.Saves(.c/0vb.net2in3ormations.*ls."
#*cel.8lFileFormat.*l+orkbook-ormal" misValue" misValue" misValue" misValue" _
#*cel.8lSavesccess5ode.*l#*clusive" misValue" misValue" misValue"
misValue" misValue%
*l+orkBook.Close('rue" misValue" misValue%
*lpp.Cuit(%
releaseOb!ect(*l+orkS4eet%
releaseOb!ect(*l+orkBook%
releaseOb!ect(*lpp%
5essa$eBo*.S4o)(.Over.%
#nd Sub
Private Sub releaseOb!ect(ByVal ob! s Ob!ect%
'ry
System.6untime.InteropServices.5ars4al.6eleaseComOb!ect(ob!%
ob! , -ot4in$
Catc4 e* s #*ception
ob! , -ot4in$
5essa$eBo*.S4o)(.#*ception Occured )4ile releasin$ ob!ect . N
e*.'oStrin$(%%
Finally
9C.Collect(%
#nd 'ry
#nd Sub
#nd Class
*o( to Import data !rom Excel to Data4ridVie(
The ,ata7ridView control and its related classes are designed to be a fle+ible, e+tensible system
for displaying and editing tabular data. ?ou can use a ,ata7ridView control to display data with
or without an underlying data source.
The following vb.net source code shows how to )mport data from an E+cel file to a
,ata7ridView control .
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
Private Sub Button1_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles Button1.Click
(im 5yConnection s System.(ata.Ole(b.Ole(bConnection
(im (tSet s System.(ata.(ataSet
(im 5yCommand s System.(ata.Ole(b.Ole(b(atadapter
5yConnection , -e)
System.(ata.Ole(b.Ole(bConnection(.provider,5icroso3t.Met.O1#(B.G.;O(ata
Source,Dc/0vb.net2in3ormations.*lsDO#*tended Properties,#*cel J.;O.%
5yCommand , -e) System.(ata.Ole(b.Ole(b(atadapter(.select P 3rom
?S4eet1Q@." 5yConnection%
5yCommand.'able5appin$s.dd(.'able." .-et2in3ormations.com.%
(tSet , -e) System.(ata.(ataSet
5yCommand.Fill((tSet%
(ata9ridVie)1.(ataSource , (tSet.'ables(;%
5yConnection.Close(%
#nd Sub
#nd Class
Data$ase operations in DatagridVie(
The ,ata7ridView control can display rows of data from a data source. The ,ata7ridView can
display data in Bound mode, unbound mode and Virtual mode . Bound mode is suitable for
managing data using automatic interaction with the data store. ne very common use of the
,ata7ridView control is binding to a table in a database. 3nbound mode is suitable for
displaying relatively small amounts of data that you manage programmatically. Virtual mode
gives you a higher degree of control by allowing you to wait until a cell is actually being
displayed to provide the value it will contain.
The following vb.net source code illustrate how to connect a ,ata7ridView to a database and
addnew@update or delete the database values from ,ata7ridView.
Do$nload Source !ode
Print Source !ode
Imports System.(ata.S:lClient
Public Class Form1
(im sCommand s S:lCommand
(im sdapter s S:l(atadapter
(im sBuilder s S:lCommandBuilder
(im s(s s (ataSet
(im s'able s (ata'able
Private Sub load_btn_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles load_btn.Click
(im connectionStrin$ s Strin$ , .(ata Source,.OInitial
Catalo$,pubsOInte$rated Security,'rue.
(im s:l s Strin$ , .S#1#C' P F6O5 Stores.
(im connection s -e) S:lConnection(connectionStrin$%
connection.Open(%
sCommand , -e) S:lCommand(s:l" connection%
sdapter , -e) S:l(atadapter(sCommand%
sBuilder , -e) S:lCommandBuilder(sdapter%
s(s , -e) (ataSet(%
sdapter.Fill(s(s" .Stores.%
s'able , s(s.'ables(.Stores.%
connection.Close(%
(ata9ridVie)1.(ataSource , s(s.'ables(.Stores.%
(ata9ridVie)1.6eadOnly , 'rue
save_btn.#nabled , False
(ata9ridVie)1.Selection5ode , (ata9ridVie)Selection5ode.Full6o)Select
#nd Sub
Private Sub ne)_btn_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles ne)_btn.Click
(ata9ridVie)1.?6eadOnly@ , False
save_btn.#nabled , 'rue
ne)_btn.#nabled , False
delete_btn.#nabled , False
#nd Sub
Private Sub delete_btn_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles delete_btn.Click
I3 5essa$eBo*.S4o)(.(o you )ant to delete t4is ro) Y." .(elete."
5essa$eBo*Buttons.Res-o% , (ialo$6esult.Res '4en
(ata9ridVie)1.6o)s.6emovet((ata9ridVie)1.Selected6o)s(;%.Inde*%
sdapter.Fpdate(s'able%
#nd I3
#nd Sub
Private Sub save_btn_Click(ByVal sender s System.Ob!ect" ByVal e s
System.#ventr$s% &andles save_btn.Click
sdapter.Fpdate(s'able%
(ata9ridVie)1.?6eadOnly@ , 'rue
save_btn.#nabled , False
ne)_btn.#nabled , 'rue
delete_btn.#nabled , 'rue
#nd Sub
#nd Class