[go: up one dir, main page]

0% found this document useful (0 votes)
441 views293 pages

Vb.net

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 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 Office applications built on the .NET Framework. The Visual Basic language
is designed to be human readable and accessible to everyone from novice programmers to
advanced system architects. All of this is built on top of the .NET Framework, which guarantees
that programs written in Visual Basic run with unsurpassed scalability and reliability. Programs
written in Visual Basic will interoperate seamlessly with programs written in any other .NET
languages such as Visual C#, Visual J#, or Visual C++.
I hope this site will help you to acquire the skills and knowledge necessary to develop Windows
applications in VB.NET in a simplified manner rather than in a complex way.
The Microsoft .Net Framework is a platform that provides tools and technologies you need to
build Networked Applications as well as Distributed Web Services and Web Applications. The
.Net Framework provides the necessary compile time and run-time foundation to build and run
any language that conforms to the Common Language Specification (CLS).The main two
components of .Net Framework are Common Language Runtime (CLR) and .Net Framework
Class Library (FCL).

The Common Language Runtime (CLR) is the runtime environment of the .Net Framework , that
executes and manages all running code like a Virtual Machine. The .Net Framework Class
Library (FCL) is a huge collection of language-independent and type-safe reusable classes.
The .Net Framework Class Libraries (FCL) are arranged into a logical grouping according to
their functionality and usability is called Namespaces. In the following sections describes how to
.Net Framework manages the code in compile time and run time.
Microsoft .Net Languages Source Code are compiled into Microsoft Intermediate Language
(MSIL) . MSIL we can call it as Intermediate Language (IL) or Common Intermediate Language

(CIL). Microsoft Intermediate Language (MSIL) is a CPU independent set of instructions that
can be converted to the native code. Metadata also created in the course of compile time with
Microsoft Intermediate Language (MSIL) 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 Common
Language Runtime (CLR) needs for execution .

The Common Language Runtime (CLR) uses metadata to locate and load classes, generate
native code, provide security, and execute Managed Code. Both Microsoft Intermediate
Language (MSIL) and Metadata assembled together is known as Portable Executable (PE) file.
Portable Executable (PE) is supposed to be portable across all 32-bit operating systems by
Microsoft .Net Framework.
During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler
converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating
System. The native code is Operating System independent and this code is known as Managed
Code , that is, the language's functionality is managed by the .NET Framework . The Common
Language Runtime (CLR) provides various Just In Time (JIT) compilers, and each works on a
different architecture depends on Operating Systems, that means the same Microsoft
Intermediate Language (MSIL) can be executed on different Operating Systems. In the following
section you can see how Common Language Runtime (CLR) functions .
The Common Language Runtime (CLR) is an Execution Environment. It works as a layer
between Operating Systems and the applications written in .Net languages that conforms to the
Common Language Specification (CLS). The main function of Common Language Runtime
(CLR) is to convert the Managed Code into native code and then execute the Program. The
Managed Code compiled only when it needed, that is it converts the appropriate instructions
when each function is called . The Common Language Runtime (CLR) 's Just In Time (JIT)
compilation converts Intermediate Language (MSIL) to native code on demand at application run
time.
During the execution of the program ,the Common Language Runtime (CLR) manages memory,
Thread execution, Garbage Collection (GC) , Exception Handling, Common Type System (CTS),
code safety verifications, and other system services. The CLR (Common Language Runtime )
defines the Common Type System (CTS), which is a standard type system used by all .Net
languages . That means all .NET programming languages uses the same representation for
common Data Types , so Common Language Runtime (CLR) is a language-independent runtime
environment. The Common Language Runtime (CLR) environment is also referred to as a

managed environment, because during the execution of a program it also controls the interaction
with the Operating System. In the coming section you can see what are the main functions of
Common Language Runtime (CLR).
The Common Language Runtime (CLR) is a an Execution Environment . Common Language
Runtime (CLR)'s main tasks are to convert the .NET Managed Code to native code, manage
running code like a Virtual Machine and also controls the interaction with the Operating System.
Common Language Runtime (CLR) manages Thread executions, Memory Management that is
allocation of Objects and Buffers , Garbage Collection (GC) - Clean up the unused Objects and
buffers , Exception Handling, Common Type System (CTS) that is all .NET language that
conforms to the Common Language Specification (CLS) have the same primitive Data Types,
Code safety verifications - code can be verified to ensure type safety, Language integration that
is Common Language Runtime (CLR) follow a set of specification called Common Language
Specification (CLS) , this will ensure the interoperability between languages, Integrated security
and other system services.
The .Net Framework class library (FCL) provides the core functionality of .Net Framework
architecture . The .Net Framework Class Library (FCL) includes a huge collection of reusable
classes , interfaces, and value types that expedite and optimize the development process and
provide access to system functionality.
The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is
divided into Namespaces. Namespaces is a logical grouping of types for the purpose of
identification. Framework class library (FCL) provides the consistent base types that are used
across all .NET enabled languages. The Classes are accessed by namespaces, which reside within
Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net
Framework class library (FCL) classes are managed classes that provide access to System
Services . The .Net Framework class library (FCL) classes are object oriented and easy to use in
program developments. Moreover, third-party components can integrate with the classes in
the .NET Framework.
Common Language Specification (CLS) is a set of basic language features that .Net Languages
needed to develop Applications and Services , which are compatible with the .Net Framework.
When there is a situation to communicate Objects written in different .Net Complaint languages ,
those objects must expose the features that are common to all the languages . Common Language
Specification (CLS) ensures complete interoperability among applications, regardless of the
language used to create the application.
Common Language Specification (CLS) defines a subset of Common Type System (CTS) .
Common Type System (CTS) describes a set of types that can use different .Net languages have
in common , which ensure that objects written in different languages can interact with each other.
Most of the members defined by types in the .NET Framework Class Library (FCL) are
Common Language Specification (CLS) compliant Types. Moreover Common Language
Specification (CLS) standardized by ECMA .

Common Type System (CTS) describes a set of types that can be used in different .Net languages
in common . That is , the Common Type System (CTS) ensure that objects written in different
.Net languages can interact with each other. For Communicating 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 Reference Types . The Value Types are passed by values and
stored in the stack. The Reference Types are passed by references and stored in the heap.
Common Type System (CTS) provides base set of Data Types which is responsible for cross
language integration. The Common Language Runtime (CLR) can load and execute the source
code written in any .Net language, only if the type is described in the Common Type System
(CTS) .Most of the members defined by types in the .NET Framework Class Library (FCL) are
Common Language Specification (CLS) compliant Types.
MSIL stands for Microsoft Intermediate Language. We can call it as Intermediate Language (IL)
or Common Intermediate Language (CIL). During the compile time , the compiler convert the
source code into Microsoft Intermediate Language (MSIL) .Microsoft Intermediate Language
(MSIL) is a CPU-independent set of instructions that can be efficiently converted to the native
code. During the runtime the Common Language Runtime (CLR)'s Just In Time (JIT) compiler
converts the Microsoft Intermediate Language (MSIL) code into native code to the Operating
System.
When a compiler produces Microsoft Intermediate Language (MSIL), it also produces Metadata.
The Microsoft Intermediate Language (MSIL) and Metadata are contained in a portable
executable (PE) file . Microsoft Intermediate Language (MSIL) includes instructions for loading,
storing, initializing, and calling methods on objects, as well as instructions for arithmetic and
logical operations, control flow, direct memory access, exception handling, and other operations
The Portable Executable (PE) format is a file format for executables, object code, and DLLs,
used in 32-bit and 64-bit versions of Windows operating systems.
The PE file format was defined to provide the best way for the Windows Operating System to
execute code and also to store the essential data which is needed to run a program. Portable
Executable File Format is derived from the Microsoft Common Object File Format (COFF).
The .Net languages , which is conforms to the Common Language Specification (CLS), uses its
corresponding runtime to run the application on different Operating Systems . During the code
execution time, the Managed Code compiled only when it is needed, that is it converts the
appropriate instructions to the native code for execution just before when each function is called.
This process is called Just In Time (JIT) compilation, also known as Dynamic Translation . With
the help of Just In Time Compiler (JIT) the Common Language Runtime (CLR) doing these
tasks.
The Common Language Runtime (CLR) provides various Just In Time compilers (JIT) and each
works on a different architecture depending on Operating System. That is why the same
Microsoft Intermediate Language (MSIL) can be executed on different Operating Systems
without rewrite the source code. Just In Time (JIT) compilation preserves memory and save time

during application initialization. Just In Time (JIT) compilation is used to run at high speed, after
an initial phase of slow interpretation. Just In Time Compiler (JIT) code generally offers far
better performance than interpreters.
Managed Code in Microsoft .Net Framework, is the code that has executed by the Common
Language Runtime (CLR) environment. On the other hand Unmanaged Code is directly executed
by the computer's CPU. Data types, error-handling mechanisms, creation and destruction rules,
and design guidelines vary between managed and unmanaged object models.
The benefits of Managed Code include programmers convenience and enhanced security .
Managed code is designed to be more reliable and robust than unmanaged code , examples are
Garbage Collection , Type Safety etc. The Managed Code running in a Common Language
Runtime (CLR) cannot be accessed outside the runtime environment as well as cannot call
directly from outside the runtime environment. This makes the programs more isolated and at the
same time computers are more secure . Unmanaged Code can bypass the .NET Framework and
make direct calls to the Operating System. Calling unmanaged code presents a major security
risk.
Metadata in .Net is binary information which describes the characteristics of a resource . This
information include Description of the Assembly , Data Types and members with their
declarations and implementations, references to other types and members , Security permissions
etc. A module's metadata contains everything that needed to interact with another module.
During the compile time Metadata created with Microsoft Intermediate Language (MSIL) and
stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL)
together wrapped in a Portable Executable (PE) file. During the runtime of a program Just In
Time (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts
Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime
loads metadata into memory and references it to discover information about your code's classes,
members, inheritance, and so on. Moreover Metadata eliminating the need for Interface
Definition Language (IDL) files, header files, or any external method of component reference.
Microsoft .Net Assembly is a logical unit of code, it contains code that the Common Language
Runtime (CLR) executes. Assembly is really a collection of types and resource information that
are built to work together and form a logical unit of functionality. During the compile time
Metadata is created, with Microsoft Intermediate Language (MSIL), and stored in a file called a
Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a
Portable Executable (PE) file. Manifest contains information about itself. This information is
called Assembly Manifest, it contains information about the members, types, references and all
the other data that the runtime needs for execution.
Every Assembly you create contains one or more program files and a Manifest. There are two
types program files : Process Assemblies (EXE) and Library Assemblies (DLL). Each Assembly
can have only one entry point (that is, DllMain, WinMain, or Main). We can create two types of
Assembly, private Assembly and shared Assembly . A private Assembly is used only by a single
application, and usually it is stored in that application's install directory. A shared Assembly is

one that can be referenced by more than one application. If multiple applications need to access
an Assembly, we should add the Assembly to the Global Assembly Cache (GAC).
An Assembly Manifest is a file that containing Metadata about .NET Assemblies. Assembly
Manifest contains a collection of data that describes how the elements in the assembly relate to
each other. It describes the relationship and dependencies of the components in the Assembly,
versioning information, scope information and the security permissions required by the
Assembly.
The Assembly Manifest can be stored in Portable Executable (PE) file with Microsoft
Intermediate Language (MSIL) code. You can add or change some information in the Assembly
Manifest by using assembly attributes in your code. The Assembly Manifest can be stored in
either a PE file (an .exe or .dll) with Microsoft Intermediate Language (MSIL) code or in a
standalone PE file that contains only assembly manifest information. Using ILDasm, you can
view the manifest information for any managed DLL.

Each computer on which the Common Language Runtime is installed has a machine-wide code
cache called the 'Global Assembly Cache'. The Global Assembly Cache (GAC) enables you to
share assemblies across numerous applications.
The GAC is automatically installed with the .NET runtime. The global assembly cache is located
in 'Windows/WinNT' directory and inherits the directory's 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 drawbacks like DLL hell.
The Global Assembly Cache Tool (Gacutil.exe), that allows you to view and manipulate the
contents of the Global Assembly Cache.
A .NET Framework assembly containing resources specific to a given language. Using 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. In general, assemblies should contain culture-neutral resources. If you want to localize
your assembly (for example use different strings for different locales) you should use satellite
assemblies.
Use the Assembly Linker (Al.exe) to compile .resources files into satellite assemblies. Al.exe
creates an assembly from the .resources files that you specify. By definition, satellite assemblies
can only contain resources. They cannot contain any executable code.
A .NET static assembly can consist of following elements:
a) Assembly Manifest - The Metadata that describes the assembly and its contents

b) Type Metadata - Defines all types, their properties and methods.


c) MSIL - Microsoft intermediate language
d) A set of Resources - All other resources like icons, images etc.
Only the assembly manifest is required, but either types or resources are needed to give the
assembly in any meaningful functionality.
A private assembly is an assembly that is available to particular application where they are kept,
and a Shared Assembly is a public assembly that is shared by multiple applications. That means,
a Private Assembly cannot be references outside the scope of the folder where they are kept and
a Shared Assembly is one that can be referenced by more than one application.
In order to share an assembly, the assembly must be explicitly built for this purpose by giving it a
cryptographically strong name . By contrast, a private assembly name need only be unique
within the application that uses it.
The classes that ship with the .NET Framework are all built as shared assemblies.
Strong name consists of an Assemblys identity, that means the Assemblies can be assigned a
cryptographic signature. The strong name guarantees the integrity of the assembly which
prevents someone from taking over the name of the assembly.
Strong Name includes the name of the .net assembly, version number, culture identity, and a
public key token. It is generated from an assembly file using the corresponding private key.
Strong names guarantee name uniqueness by relying on unique key pairs.
To create a key pair
At the command prompt, type the following command:
sn -k fileName
In this command, file name is the name of the output file containing the key pair.
Namespaces are the way to organize .NET Framework Class Library 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 Framework Class Library (FCL ) is a large collection of thousands of Classes. These
Classes are organized in a hierarchical tree. The System Namespaces is the root for types in
the .NET Framework. We can uniquely identify any Class in the .NET Framework Class Library
(FCL ) by using the full Namespaces of the class .In .Net languages every program is created
with a default Namespaces . Programmers can also create their own Namespaces in .Net
languages.

An 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. All objects created within the same application scope are created within the same
application domain. Multiple application domains can exist in a single operating system process.
An application running inside one application domain cannot directly access the code running
inside another application domain.
System.AppDomain is the main class you can use to deal with application domains.
The .NET Security Model provides code access permissions and code identity permissions. Code
Access Security 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. Code Access Security policy
uses evidence to help grant the right permissions to the right assembly.
An administrator can configure Code Access Security policy to restrict the resource types that
code can access and the other privileged operations it can perform. Code Access Security allows
code to be trusted to varying degrees depending on where the code originates and on other
aspects of the code's identity. Code Access Security can also help minimize the damage that can
result from security vulnerabilities in your code.
The .Net Framework provides a new mechanism for releasing unreferenced objects from the
memory (that is we no longer needed that objects in the program) ,this process is called Garbage
Collection (GC). When a program creates an Object, the Object takes up the memory. Later
when the program has no more references to that Object, the Object's memory becomes
unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are
any Objects in the heap that are no longer being used by the application. If such Objects exist,
then the memory used by these Objects can be reclaimed. So these unreferenced Objects should
be removed from memory , then the other new Objects you create can find a place in the Heap.
The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after
itself when it is being collected. This releasing of unreferenced Objects is happening
automatically in .Net languages by the Garbage Collector (GC). The programming languages
like C++, programmers are responsible for allocating memory for Objects they created in the
application and reclaiming the memory when that Object is no longer needed for the program.
In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the
program by calling System.GC.Collect.
Thread in computer science means a sequence of execution instructions that can run
independently , that is a single flow of execution in a process. Thread is like a process, at least
one thread exists within each process. Single Thread (normal programs) in computer science
means that only one task can execute and at the same time the other tasks have to wait for the
completion of the current task like in a queue. Single thread resulted in systems idle time and
application performance.

Multithreading allows multiple process to execute concurrently within a single program .That is
more than one task in a program can execute at the same time and each thread run independently
of its own. If multiple threads can exist within a process, typically share the state information of
a process, and share memory and other resources directly. Each thread maintains exception
handlers, a scheduling priority, and a set of structures the system uses to save the thread context
until it is scheduled.
In multiple threaded programming we can use system's idle time, so it leads improved
application performance . Also we can set priority in each Threads . Threads with higher priority
are executed in preference to threads with lower priority. It is recommended that you use as few
threads as possible, thereby minimizing the use of Operating System resources . Check the
following links to see how Multi Threaded applications works in VB.NET .
1. Multithreaded Socket Programming
2. Multi Threaded Chat Server Program

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 : Dim VariableName as DataType
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 example shows , declare a variable 'count' for holding integer values.
In the variable count we can hold the integer values in
the range of -2,147,483,648 to +2,147,483,647.
The follwing are the some of commonly using datatypes in vb.net.
Boolean

Boolean variables are stored 16 bit numbers and it can hold only True or false.
VB.NET Runtime type : System.Boolean
VB.NET declaration : dim check as Boolean
VB.NET Initialization : check = false
VB.NET default initialization value : false
Integer
Integer variables are stored sighned 32 bit integer values in the range of -2,147,483,648 to
+2,147,483,647
VB.NET Runtime type : System.Int32
VB.NET declaration : dim count as Integer
VB.NET Initialization : count = 100
VB.NET default initialization value : 0
String
String variables are stored any number of alphabetic, numerical, and special characters . Its
range from 0 to approximately 2 billion Unicode characters.
VB.NET Runtime type : System.String
VB.NET declaration : Dim str As String
VB.NET Initialization : str = "String Test"
VB.NET default initialization value : Nothing
In VisualBasic.Net we can convert a datatype in two ways. Implicit Conversion and Explicit
conversion . Also we can convert a type value to a reference and reference value to a type value.
These are called Boxing and unBoxing . Boxing referes value type to reference type and
unboxing , reference type ot value type.

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim check As Boolean

check = True
MsgBox("The value assigned for check is : " & check)
Dim count As Integer
count = 100
MsgBox("The value holding count is : " & count)
Dim str As String
str = "String test "
MsgBox("The value holding str is : " & str)
End Sub
End Class

When you execute this programme , you will get "true" in the first message box and , 100 in the
second message box and "String Test" in the last message box.
Implicit Type Conversions
Implicit Conversion perform automatically in VB.NET, that is the compiler is taking care of the
conversion.
The following example you can see how it happen.
1. Dim iDbl As Double
2. Dim iInt As Integer
3. iDbl = 9.123
4. MsgBox("The value of iDbl is " iDbl)
5. iInt = iDbl
6. MsgBox("The value of iInt is " iInt)
line no 1 : Declare a Double datatype variable iDble
line no 2 : Declare an Integer datatyoe variable iInt
line no 3 : Assign a decimal value to iDbl
line no 4 : Display the value of iDbl
line no 5 : Assign the value of iDbl to iInt
line no 6 : Display the value of iInt
The first messagebox display the value of iDbl is 9.123
The second messegebox display the value od iInt is 9
iInt display only 9 because the value is narrowed to 9 to fit in an Integer variable.
Here the Compiler made the conversion for us. These type fo conversions are called Implicit
Conversion .
The Implicit Conversion perform only when the Option Strict switch is OFF
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim iDbl As Double
Dim iInt As Integer
iDbl = 9.123
MsgBox("The value of iDbl is " & iDbl)
iInt = iDbl

'after conversion
MsgBox("The value of iInt is " & iInt)
End Sub
End Class

Explicit Type Conversions


In 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 conversion . An explicit
conversion uses a type conversion keyword. With these conversion keywords we hav to perform
the Explicit Conversion.
AccessSpecifiers describes as the scope of accessibility of an Object and its members. We can
control the scope of the member object 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 :
Public, Private , Protected , Friend and ProtectedFriend .
Public :
Public is the most common access specifier. It 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.
Private :
The scope of the accessibility is limited only inside the classes in which they are decleared. The
Private 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 (Inherited )from this
class.
Friend :
The Friend access specifier can access within the program that contain its declarations and also
access within the same assembly level. You can use friend instead of Dim keyword.
Protected Friend:
ProtectedFriend is same access lebels of both Protected and Friend. It 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 execution . For
ex: you programme run out of memory , file does not exist in the given path , network
connections are dropped etc. More specifically for better understanding, we can say it as
Runtime Errors .
In .NET languages, Structured Exceptions handling is a fundamental part of Common
Language Runtime. It has a number of advantages over the On Error statements provided in
previous versions of Visual Basic. All exceptions in the Common Language Runtime are derived
from a single base class , also you can create your own custom Exception classes. You can create
an Exception class that inherits from Exception class .
You can handle Exceptions using Try..Catch statement.
Try
code
exit from Try
Catch [Exception [As Type]]
code - if the exception occurred this code will execute
exit from Catch

Finally
The code in the finally block will execute even if there is no Exceptions. That means if you write
a finally block , the code should execute after the execution of try block or catch block.
Try
code
exit from Try
Catch [Exception [As Type]]
code - if the exception occurred this code will execute
exit Catch
Finally
code - this code should execute , if exception occurred or not

From the following VB.NET code , you can understand how to use try..catch statements. Here
we are going to divide a number by zero .
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim i As Integer
Dim resultValue As Integer
i = 100
resultValue = i / 0
MsgBox("The result is " & resultValue)

Catch ex As Exception
MsgBox("Exception catch here ..")
Finally
MsgBox("Finally block executed ")
End Try
End Sub

When you execute this program you will "Exception catch here .." first and then "Finally
block executed " . That is when you execute this code , an exception happen and it will go to
catch block and then it will go to finally block.
Option Explicit statement ensures whether the compiler requires all variables to be explicitly
declared or not before it use in the program.
Option Explicit [On Off]
The Option Explicit has two modes. On and Off mode. If Option Explicit mode in ON , you
have to declare all the variable before you use it in the program . If not , it will generate a
compile-time error whenever a variable that has not been declared is encountered .If the Option
Explicit mode is OFF , Vb.Net automatically create a variable whenever it sees a variable
without proper declaration.
By default the Option Explicit is On
With the Option Explicit On , you can reduce the possible errors that result from misspelled
variable names. Because in Option Explicit On mode you have to declare each variable in the
program for storing data.
Take a look at the following programs, it will give you a clear picture of Option Explicit.
The following program is a normal vb.net program , so the default mode of Option Explicit On is
using. The default is Option Explicit On , so we do not need to put it in the source code.
VB.NET Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim someVariable As String
someVariable = "Option Explicit ON"
MsgBox(someVariable)
End Sub
End Class

The above program , declare a String variable and assigned a value in it and it displays.
Take a look at the following program , it is an example of Option Explicit Of

Here "someVariable" is not declared , because the Option Explicit Of , without any compiler
error you can continue the program.
Option Strict is prevents program from automatic variable conversions, that is implicit data type
conversions .
Option Strict [On Off]
By default Option Strict is Off
From the following example you can understand the use of Option Strict.
VB.NET Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim longNum As Long
Dim intNum As Integer
longNum = 12345
intNum = longNum
MsgBox(intNum)
End Sub
End Class

The above program is a normal vb.net program and is in default Option Strict Off . Because its
Option Strict Off we can convert the value of Long to an Integer.
When you write this source code the compiler will shows the message
"Option Strict On disallows implicit conversions from 'Long' to 'Integer'"
The compiler generate error because in the program we put "Option Strict On" and prevent the
program from automatic conversion.
On Error GoTo statements is an example of Vb.Net's Unstructured Exception Handling .
VB.NET has two types of Exception handling . Structured Error Handling and Unstructured
Error handling . VB.NET using Try..Catch statement for Structured Error handling and On
Error GoTo statement is using for Unstructured Error handling.
Error GoTo redirect the flow of the program in a given location.
On Error Resume Next - whenever an error occurred in runtime , skip the statement and
continue execution on following statements.
Take a look at the following program

VB.NET Source Code


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim result As Integer
Dim num As Integer
num = 100
result = num / 0
MsgBox("here")
End Sub
End Class

when u execute this program you will get error message like " Arithmetic operation resulted in
an overflow "
See the program we put an On Error GoTo statement
When you execute the program you will get the message box "Control Here" . Because the On
Error statement redirect the exception to the Label statement.
The conditional statement IF ELSE , is use for examining the conditions that we provided, and
making decision based on that contition. The conditional statement examining the data using
comparison operators as well as logical operators.
If [your condition here]
Your code here
Else
Your code Here
End If

If the contition is TRUE then the control goes to between IF and Else block , that is the program
will execute the code between IF and ELSE statements.
If the contition is FLASE then the control goes to between ELSE and END IF block , that is the
program will execute the code between ELSE and END IF statements.
If you want o check more than one condition at the same time , you can use ElseIf .
If [your condition here]
Your code here
ElseIf [your condition here]
Your code here
ElseIf [your condition here]
Your code here
Else
Your code Here
End If

Just take a real-time example - When we want to analyze a mark lists we have to apply some
conditions for grading students depends on the marks.
Following are the garding rule of the mark list:
1) If the marks is greater than 80 then the student get higher first class
2) If the marks less than 80 and greater than 60 then the student get first class
3) If the marks less than 60 and greater than 40 then the student get second class
4) The last condition is , if the marks less than 40 then the student fail.
Now here implementing these conditions in a VB.NET program.
1.
2.
3.
4.
5.
6.
7.
8.
9.

If totalMarks >= 80 Then


MsgBox("Got Higher First Class ")
ElseIf totalMarks >= 60 Then
MsgBox("Got First Class ")
ElseIf totalMarks >= 40 Then
MsgBox("Just pass only")
Else
MsgBox("Failed")
End If

Line 1 : Checking the total marks greaterthan or equal to 80


Line 2 : If total marks greater than 80 show message - "Got Higher First Class "
Line 3 : Checking the total marks greaterthan or equal to 60
Line 4 : If total marks greater than 60 show message - "Got First Class "
Line 5 : Checking the total marks greaterthan or equal to 40
Line 6 : If total marks greater than 40 show message - "Just pass only"
Line 7 : If those three conditions failed program go to the next coding block
Line 8 : If all fail shows message "Failed"
Line 9 : Ending the condition block
VB.NET Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,

ByVal e As System.EventArgs) Handles Button1.Click


Dim totalMarks As Integer
totalMarks = 59
If totalMarks >= 80 Then
MsgBox("Gor Higher First Class ")
ElseIf totalMarks >= 60 Then
MsgBox("Gor First Class ")
ElseIf totalMarks >= 40 Then
MsgBox("Just pass only")
Else
MsgBox("Failed")
End If
End Sub
End Class

In this example the total marks is 59 , when you execute this program you will get in
messagebox "Just Pass Only"
If you want to check a condition within condition you can use nested if statements
If [your condition here]
If [your condition here]
Your code here
Else
Your code Here
End If
Else
Your code Here
End If

Also you can write IF ELSE Statements in a single line


If [your condition here] [Code] Else [code]
When you execute this program you will get in messagebox "Failed "
Whenever you face a situation in programming to repeat a task for several times (more than one
times ) or you have to repeat a task till you reach a condtition, in these situations you can use
loop statements to achieve your desired results.
FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly
used loops in Visual Basic.NET 2005 ( VB.NET 2005) .
FOR NEXT Loop :
The FOR NEXT Loop , execute the loop body (the source code within For ..Next code block) to
a fixed number of times.

For var=[startValue] To [endValue] [Step]


[loopBody]
Next [var]

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 Loop will stop .
loopBody : The source code between loop body
Lets take a simple real time example , If you want to show a messagebox 5 times and each time
you want to see how many times the message box shows.
1.
2.
3.
4.
5.

startVal=1
endVal = 5
For var = startVal To endVal
show message
Next var

Line 1: Loop starts value from 1


Line 2: Loop will end when it reach 5
Line 3: Assign the starting value to var and inform to stop when the var reach endVal
Line 4: Execute the loop body
Line 5: Taking next step , if the counter not reach the endVal
VB.NET Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim var As Integer
Dim startVal As Integer
Dim endVal As Integer
startVal = 1
endVal = 5
For var = startVal To endVal
MsgBox("Message Box Shows " & var & " Times ")
Next var
End Sub
End Class

When you execute this program , It will show messagebox five time and each time it shows the
counter value.
If you want to Exit from FOR NEXT Loop even before completing the loop Visual Basic.NET
provides a keyword Exit to use within the loop body.
For var=startValue To endValue [Step]
[loopBody]
Contition
[Exit For]
Next [var]

Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim var As Integer
Dim startVal As Integer
Dim endVal As Integer
startVal = 1
endVal = 5
For var = startVal To endVal
MsgBox("Message Box Shows " var " Times ")
If var = 3 Then
Exit For
End If
Next var
End Sub
End Class

When you execute the above source code , the program shows the message box only three times .
Whenever you face a situation in programming to repeat a task for several times (more than one
times ) or you have to repeat a task till you reach a condition, in these situations you can use loop
statements to achieve your desired results.
FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly
used loops in Visual Basic.NET 2005 ( VB.NET 2005) .
For Each Loop
FOR EACH Loop usually using when you are in a situation to execute every single element or
item in a group (like every single element in an Array, or every single files in a folder or , every
character in a String ) , in these type of situation you can use For Each loop.
For Each [Item] In [Group]
[loopBody]

Next [Item]

Item : The Item in the group


Group : The group containing items
LoopBody : The code you want to execute within For Each Loop
Let's take a real time example , if you want to display the each character in the website name
"HTTP://NET-INFORMATIONS.COM" , it is convenient to use For Each Loop.
1. siteName = "HTTP://NET-INFORMATIONS.COM"
2. For Each singleChar In siteName
3.
MsgBox(singleChar)
4. Next

Line 1: Assigning the site name in a variable


Line 2: This line is extracting the single item from the group
Line 3: Loop body
Line 4: Taking the next step
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim siteName As String
Dim singleChar As Char
siteName = "HTTP://NET-INFORMATIONS.COM"
For Each singleChar In siteName
MsgBox(singleChar)
Next
End Sub
End Class

When you execute this program you will get each character of the string in Messagebox.
Whenever you face a situation in programming to repeat a task for several times (more than one
times ) or you have to repeat a task till you reach a condition, in these situations you can use loop
statements to achieve your desired results.
FOR NEXT Loop, FOR EACH Loop , WHILE Loop and DO WHILE Loop are the Commonly
used loops in Visual Basic.NET 2005 ( VB.NET 2005) .

While ..End While


While .. End While Loop execute the code body (the source code within While and End while
statements ) until it meets the specified condition.
While [condition]
[loop body]
End While

Condition : The condition set by the user


1. counter = 1
2. While (counter <= 10)
3. Message
4. counter = counter + 1
5. End While

Line 1: Counter start from 1


Line 2: While loop checking the counter if it is less than or equal to 10
Line 3: Each time the Loop execute the message and show
Line 4: Counter increment the value of 1 each time the loop execute
Line 5: End of the While End While Loop body
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim counter As Integer
counter = 1
While (counter <= 10)
MsgBox("Counter Now is : " counter)
counter = counter + 1
End While
End Sub
End Class

When you execute the program 10 times the message shows with counter and exit from the
While .. End While loop.

IDE
Visual Studio is a powerful and customizable programming environment that contains all the
tools you need to build programs quickly and efficiently. It 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 frequently using programming tools in Visual
Studio IDE

1. Menu Bar
2. Standard Toolbar
3. Tool Box
4. Forms Designer
5. Output Window
6. Solution Explorer
7. Properties Window

Visual Basic.NET IDE is built out of a collection of different windows. Some 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 Studio organizes your work in projects and solutions. A solution can contain more than
one project, such as a DLL and an executable that references that DLL. From the following
chapters you will learn how to use these Visual Studio features for your programming needs.

WINDOWS FORMS
VB.Net programmers have made extensive use of forms to build user interfaces. Each time you
create a Windows application, Visual Studio will display a default blank form, onto which you
can drag and drop controls from the Visual Studio Toolbox window.
The first job is to start a new project and build a form. Open your Visual Studio and select File>NewProject and select Visual Basic from the New project dialog box and select Windows
Froms Application. Enter a project name and click OK button. The following picture shows how
to crate a new Form in Visual Studio.

Select project type from New project dialog Box

When you add a Windows Form to your project, many of the forms properties are set by default.
Although these values are convenient, they will not always suit your programming needs. The
following picture shows how is the default Form look like.

At the top of the form there is a title bar which displays the forms title. Form1 is the default
name, you can change the name to your convenience . The title bar also includes the control box,
which holds the minimize, maximize, and close buttons. If you want to set any properties of the
Form, you can use Visual Studio Property window to change it.

For example , to change the forms title from Form1 to MyForm, click on Form1 and move to the
right side down Properties window, set Text property to MyForm. Then you can see the Title of
the form is changed. Likewise you can set any properties of Form through Properties window.
You can also set the properties of the Form1 through coding.
For example , if you want to change the back color of the form to Brown , you can code like this.
Me.BackColor = Color.Brown
Likwise you can change other properties of Form1 through coding.
The following VB.Net source code shows how to change the Title, BackColor, Size, Location
and MaximizeBox properties of Form1. Copy and paste the following VB.Net source code to
source code editor of your Visual Studio.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object,
System.EventArgs) Handles MyBase.Load
Me.Text = "Change Prperties Through Coding"
Me.BackColor = Color.Brown
Me.Size = New Size(350, 125)
Me.Location = New Point(300, 300)
Me.MaximizeBox = False
End Sub
End Class

ByVal

As

OUTPUT
When you execute (press F5 key) the program the form is look like the following image.

The Windows based programs you create using Visual Basic .NET run in the context of a form.
When you close the form, the application also ends.

Microsoft Visual Studio .NET controls are the graphical tools you use to build the user interface
of a VB.Net program. Labels are one of the most frequently used Visual Basic control.
LABEL
A Label control lets you place descriptive text , where the text does not need to be changed by
the user. The Label class is defined in the System.Windows.Forms namespace.

Add a Label control to the form. Click Label in the Toolbox and drag it over the forms Designer
and drop it in the desired location.
If you want to change the display text of the Label, you have to set a new text to the Text
property of Label.
Label1.Text = "This is my first Label"

You can load Image in Label control , if you want to load an Image in the Lable control you can
code like this
Label1.Image = Image.FromFile("C:\testimage.jpg")

The following source code shows how to set some properties of the Label through coding.
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = "This is my first Label"
Label1.BorderStyle = BorderStyle.FixedSingle
Label1.TextAlign = ContentAlignment.MiddleCenter
End Sub
End Class

TEXT BOX
VB.Net provides several mechanisms for gathering input in a program. A TextBox control is
used to display, or accept as input, a single line of text.

VB.Net programmers make extensive use of the TextBox control to let the user view or enter
large amount of text. A text box object is used to display text on a form or to get user input while
a VB.Net program is running. In a text box, a user can type data or paste it into the control from
the clipboard.
For displaying a text in a TextBox control , you can code like this
TextBox1.Text = "http://vb.net-informations.com"

You can also collect the input value from a TextBox control to a variable like this way
Dim var As String
var = TextBox1.Text

when a program wants to prevent a user from changing the text that appears in a text box, the
program can set the controls Readonly property is to True.
TextBox1.ReadOnly = True

By default TextBox accept single line of characters , If you need to enter more than one line in a
TextBox control, you should change the Multiline property is to True.
TextBox1.Multiline = True

Sometimes you want a textbox to receive password from the user. In order to keep the password
confidential, you can set the PasswordChar property of a textbox to a specific character.

TextBox1.PasswordChar = "*"

The above code set the PasswordChar to * , so when the user enter password then it display only
* instead of other characters.
From the following VB.Net source code you can see some important property settings to a
TextBox control.
Coding
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
TextBox1.Width = 200
TextBox1.Height = 50
TextBox1.Multiline = True
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim var As String
var = TextBox1.Text
MsgBox(var)
End Sub
End Class

COMBO BOX
VB.Net controls are located in the Toolbox of the development environment, and you use them
to create objects on a form with a simple series of mouse clicks and dragging motions. The
ComboBox control , which lets the user choose one of several choices.

The user can type a value in the text field or click the button to display a drop down list. In
addition to display and selection functionality, the ComboBox also provides features that enable
you to efficiently add items to the ComboBox.
ComboBox1.Items.Add("Sunday")

You can set which item should shown while it displaying in the form for first time.
ComboBox1.SelectedItem = ComboBox1.Items(3)

When you run the above code it will show the forth item in the combobox. The item index is
starting from 0.
If you want to retrieve the displayed item to a string variable , you can code like this
Dim var As String
var = ComboBox1.Text

You can remove items from a combobox in two ways. You can remove item at a the specified
index or giving a specified item by name.
ComboBox1.Items.RemoveAt(1)

The above code will remove the second item from the combobox.
ComboBox1.Items.Remove("Friday")

The above code will remove the item "Friday" from the combobox.
The DropDownStyle property specifies whether the list is always displayed or whether the list is
displayed in a drop down. The DropDownStyle property also specifies whether the text portion
can be edited.
ComboBox1.DropDownStyle = ComboBoxStyle.DropDown

The following VB.Net source code add seven days in a week to a combo box while load event of
a Windows Form and display the fourth item in the combobox.
Source code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
ComboBox1.Items.Add("Sunday")
ComboBox1.Items.Add("Monday")
ComboBox1.Items.Add("Tuesday")
ComboBox1.Items.Add("wednesday")
ComboBox1.Items.Add("Thursday")

ComboBox1.Items.Add("Friday")
ComboBox1.Items.Add("Saturday")
ComboBox1.SelectedItem = ComboBox1.Items(3)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim var As String
var = ComboBox1.Text
MsgBox(var)
End Sub
End Class

LIST BOX

VB.Net provides several mechanisms for gathering input in a program. A Windows Forms
ListBox control displays a list of choices which the user can select from.

You can use the Add or Insert method to add items to a list box. The Add method adds new items
at the end of an unsorted list box. The Insert method allows you to specify where to insert the
item you are adding.
ListBox1.Items.Add("Sunday")

The SelectionMode property determines how many items in the list can be selected at a time. A
ListBox control can provide single or multiple selections using the SelectionMode property .
If you want to retrieve a single selected item to a variable , you can code like this
Dim var As String
var = ListBox1.SelectedItem

If you change the selection mode property to multiple select , then you will retrieve a collection
of items from ListBox1.SelectedItems property.
ListBox1.SelectionMode = SelectionMode.MultiSimple

The following VB.Net program initially fill seven days in a week while in the form load event
and set the selection mode property to MultiSimple. At the Button click event it will display the
selected items.
Source code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
ListBox1.Items.Add("Sunday")
ListBox1.Items.Add("Monday")
ListBox1.Items.Add("Tuesday")
ListBox1.Items.Add("Wednesday")
ListBox1.Items.Add("Thursday")
ListBox1.Items.Add("Friday")
ListBox1.Items.Add("Saturday")
ListBox1.SelectionMode = SelectionMode.MultiSimple
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim obj As Object
For Each obj In ListBox1.SelectedItems
MsgBox(obj.ToString)
Next
End Sub
End Class

CHECK LIST BOX


The CheckedListBox control gives you all the capability of a list box and also allows you to
display a check mark next to the items in the list box.

To add objects to the list at run time, assign an array of object references with the AddRange
method. The list then displays the default string value for each object.
Dim days As String() = {"Sunday", "Monday", "Tuesday"}
checkedListBox1.Items.AddRange(days)

You can add individual items to the list with the Add method. The CheckedListBox object
supports three states through the CheckState enumeration: Checked, Indeterminate, and
Unchecked.
CheckedListBox1.Items.Add("Sunday", CheckState.Checked)
CheckedListBox1.Items.Add("Monday", CheckState.Unchecked)
CheckedListBox1.Items.Add("Tuesday", CheckState.Indeterminate)

Source

Code

Public Class Form1


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
CheckedListBox1.Items.Add("Sunday", CheckState.Checked)
CheckedListBox1.Items.Add("Monday", CheckState.Unchecked)
CheckedListBox1.Items.Add("Tuesday", CheckState.Indeterminate)
CheckedListBox1.Items.Add("Wednesday", CheckState.Checked)
CheckedListBox1.Items.Add("Thursday", CheckState.Unchecked)
CheckedListBox1.Items.Add("Friday", CheckState.Indeterminate)
CheckedListBox1.Items.Add("Saturday", CheckState.Indeterminate)
End Sub
End Class

RADIO BUTTON
A 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 clicks on a radio button, it
becomes checked, and all other radio buttons with same group become unchecked

The radio button and the check box are used for different functions. Use 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 check box. Like check boxes, radio buttons support a Checked property that
indicates whether the radio button is selected.
Source code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
RadioButton1.Checked = True
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
If RadioButton1.Checked = True Then
MsgBox("You are selected Red !! ")
Exit Sub
ElseIf RadioButton2.Checked = True Then
MsgBox("You are selected Blue !! ")
Exit Sub
Else
MsgBox("You are selected Green !! ")
Exit Sub
End If
End Sub
End Class

CHECK BOX

Check Boxes allow the user to make multiple selections from a number of options. You can click
a check box to select it and click it again to deselect it.

CheckBoxes comes with a caption, which you can set in the Text property.
CheckBox1.Text = "Net-informations.com"

You can use the CheckBox control ThreeState property to direct the control to return the
Checked, Unchecked, and Indeterminate values. You need to set the check boxs ThreeState
property to True to indicate that you want it to support three states.
CheckBox1.ThreeState = True

To apply the same property settings to multiple CheckBox controls, use the Style property. The
following VB.Net program shows how to find a checkbox is selected or not.
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim msg As String = ""
If CheckBox1.Checked = True Then
msg = "net-informations.com"
End If
If CheckBox2.Checked = True Then
msg = msg & " vb.net-informations.com"
End If
If CheckBox3.Checked = True Then
msg = msg & " csharp.net-informations.com"
End If
If msg.Length > 0 Then
MsgBox(msg & " selected ")
Else
MsgBox("No checkbox selected")
End If
CheckBox1.ThreeState = True
End Sub
End Class

PICTURE BOX

The Windows Forms PictureBox control is used to display images in bitmap, GIF,icon, or JPEG
formats.

You can set the Image property to the Image you want to display, either at design time or at run
time. You can programmatically change the image displayed in a picture box, which is
particularly useful when you use a single form to display different pieces of information.
PictureBox1.Image = Image.FromFile("C:\testImage.jpg")

The SizeMode property, which is set to values in the PictureBoxSizeMode enumeration, controls
the clipping and positioning of the image in the display area.
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage

There are five different PictureBoxSizeMode is available to PictureBox control.


AutoSize
- Sizes the picture box to the image.
CenterImage
- Centers the image in the picture box.
Normal - Places the upper-left corner of the image at upper
left in the picture box
StretchImage

- Allows you to stretch the image in code

You can change the size of the display area at run time with the ClientSize property.
pictureBox1.ClientSize = New Size(xSize, ySize)

The following VB.Net program shows how to load a picture from a file and display it in streach
mode.
PROGRESS BAR

The ProgressBar control visually indicates the progress of a lengthy operation such as calculating
a complex result, downloading a large file from the Web etc.

The Maximum and Minimum properties define the range of values to represent the progress of a
task.
Minimum : Sets the lower value for the range of valid values for progress.
Maximum : Sets the upper value for the range of valid values for progress.
Value : This property obtains or sets the current level of progress.

By default, Minimum and Maximum are set to 0 and 100. As the task proceeds, the ProgressBar
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
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim i As Integer
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 200
For i = 0 To 200
ProgressBar1.Value = i
Next
End Sub
End Class

SCROLL BAR

The horizontal 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 text boxes,
combo boxes etc. You can set the Value property yourself in code, which moves the scroll box to
match. The controls Value property gets and sets its current numeric value.
The Minimum and Maximum properties determine the range of values that the control can
display. The following VB.Net program shows a TextBox control with scrollbars.
Source code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
TextBox1.Multiline = True
TextBox1.ScrollBars = ScrollBars.Both
End Sub
End Class

DATE AND TIME PICKER


The DateTimePicker control allows you to display and collect date and time from the user with a
specified format.

The DateTimePicker control prompts the user for a date or time using a graphical calendar with
scroll arrows. The most important property of the DateTimePicker is the Value property, which
holds the selected date and time.
DateTimePicker1.Value = "12/31/2010"

The Value property is set to the current date by default. You can use the Text property or the
appropriate
member of Value to get the date and time value.
Dim idate As String
idate = DateTimePicker1.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 Format property: Long, Short, Time, or Custom.
DateTimePicker1.Format = DateTimePickerFormat.Short

The following VB.Net program shows how to set and get the value of a DateTimePicker1
control.
Source code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load

DateTimePicker1.Format = DateTimePickerFormat.Short
DateTimePicker1.Value = "12/31/2010"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim idate As String
idate = DateTimePicker1.Value
MsgBox("Selected date is : " & idate)
End Sub
End Class

TREE VIEW
Tree View control is used to display hierarchical tree like information such as a directory
hierarchy. The top level in a tree view are root nodes that can be expanded or collapsed if the
nodes have child nodes.

The user can expand the TreeNode by clicking the plus sign (+) button, if one is displayed next
to the TreeNode, or you can expand the TreeNode by calling the TreeNode.Expand method.
When a parent node is expanded, its child nodes are visible. You can also navigate through tree
views with various properties: FirstNode, LastNode, NextNode, PrevNode, NextVisibleNode,
PrevVisibleNode.
The fullpath method of treeview control provides the path from root node to the selected node.
TreeView1.SelectedNode.FullPath

Tree nodes can optionally display check boxes. To display the check boxes, set the CheckBoxes
property of the TreeView to true.
TreeView1.CheckBoxes = True
The following Vb.Net program shows a simple demonstration of treeview control
Source code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
Dim tNode As TreeNode
tNode = TreeView1.Nodes.Add("Websites")
TreeView1.Nodes(0).Nodes.Add("Net-informations.com")
TreeView1.Nodes(0).Nodes(0).Nodes.Add("CLR")
TreeView1.Nodes(0).Nodes.Add("Vb.net-informations.com")
TreeView1.Nodes(0).Nodes(1).Nodes.Add("String Tutorial")
TreeView1.Nodes(0).Nodes(1).Nodes.Add("Excel Tutorial")
TreeView1.Nodes(0).Nodes.Add("Csharp.net-informations.com")
TreeView1.Nodes(0).Nodes(2).Nodes.Add("ADO.NET")
TreeView1.Nodes(0).Nodes(2).Nodes(0).Nodes.Add("Dataset")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
MsgBox(TreeView1.SelectedNode.FullPath)
End Sub
End Class

LIST VIEW
List views displays a collection of items that can be displayed using one of five different views,
such as LargeIcon, Details , SmallIcon, List and Tile.

ListView provides a large number of properties that provide flexibility in appearance and
behavior. The View property allows you to change the way in which items are displayed. and the
SelectionMode 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 Details and GridLines property as
true and FullRowSelect as true.
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.FullRowSelect = True

After that it fills column header and then the column values.
ListView1.Columns.Add("ProductName", 100)

Finally in the button click event, it will display the selected row values in a message box.
Source code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
MyBase.Load
''Set view property
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.FullRowSelect = True
'Add column header
ListView1.Columns.Add("ProductName", 100)
ListView1.Columns.Add("Price", 70)
ListView1.Columns.Add("Quantity", 70)
'Add items in the listview
Dim arr(3) As String
Dim itm As ListViewItem
'Add first item
arr(0) = "product_1"
arr(1) = "100"
arr(2) = "10"
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)
'Add second item
arr(0) = "product_2"
arr(1) = "200"
arr(2) = "20"
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)

End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim productName As String
Dim price As String
Dim quantity As String
productName = ListView1.SelectedItems.Item(0).SubItems(0).Text
price = ListView1.SelectedItems.Item(0).SubItems(1).Text
quantity = ListView1.SelectedItems.Item(0).SubItems(2).Text
MsgBox(productName & " , " & price & " , " & quantity)
End Sub
End Class

MENU CONTROL
A 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 MenuItem objects that
represent individual parts of a menu.
You can create a main menu object on your form using the MainMenu control. The following
picture shows how to drag the Menustrip Object to the Form.

After drag the Menustrip on your form you can directly create the menu items by type a value
into the "Type Here" box on the menubar part of your form. From the following picture you can
understand how to create each menu items on mainmenu Object.

If you need a separator bar , right click on your menu then go to insert->Separator.

After creating the Menu on the form , you have to double click on each menu item and write the
programs there depends on your requirements. The following Vb.Net program shows how to
show a messagebox when clicking a menu item.

Source code
Public Class Form1
Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MenuItem1ToolStripMenuItem.Click
MsgBox("You are selected MenuItem_1")
End Sub
End Class

MDI FORM
A Multiple Document Interface (MDI) programs can display multiple child windows inside
them.

This is in contrast to single document interface (SDI) applications, which can manipulate only
one document at a time. Visual Studio Environment is an example of Multiple Document
Interface (MDI) and notepad is an example of an SDI application, opening a document closes
any previously opened document. Any windows can become an MDI parent, if you set the
IsMdiContainer property to True.
IsMdiContainer = True

The following vb.net program shows a MDI form with two child forms. Create a new VB.Net
project, then you will get a default form Form1 . Then add two mnore forms in the project
(Form2 , Form 3) . Create a Menu on your form and call these two forms on menu click event.
Click the following link to see how to create a Menu on your form How to Menu Control
VB.Net.

Source code
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
IsMdiContainer = True
End Sub
Private Sub MenuItem1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MenuItem1ToolStripMenuItem.Click
Dim frm2 As New Form2
frm2.Show()
frm2.MdiParent = Me
End Sub
Private Sub MenuItem2ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MenuItem2ToolStripMenuItem.Click
Dim frm3 As New Form3
frm3.Show()
frm3.MdiParent = Me
End Sub
End Class

COLOR DIALOG BOX


There are several classes that implement common dialog boxes, such as color selection and print
setup etc.

The user can choose a color from either a set of basic or custom color palettes. You can invite a
color dialog box by calling ShowDialog() method.

Dim dlg As New ColorDialog


dlg.ShowDialog()

The Color dialog box 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 32-bit RGB
values that have the following hexadecimal form: 0x00bbggrr.
The following Vb.Net program invites a color dialog box and retrieve the selected color to a
string.
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim dlg As New ColorDialog
dlg.ShowDialog()
If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim str As String
str = dlg.Color.Name
MsgBox(str)
End If
End Sub
End Class

FONT DIALOG BOX


Dialog boxes consist of a title bar , an optional main instruction , various controls in the content
area , and commit buttons . The Font dialog box lets the user choose attributes for a logical font,
such as font family and associated font style, point size, effects, and a script.

The following VB.Net program invites a Font Dialog Box and retrieve the selected Font Name
and Font Size.

Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim dlg As New FontDialog
dlg.ShowDialog()
If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fontName As String
Dim fontSize As Integer
fontName = dlg.Font.Name
fontSize = dlg.Font.Size
MsgBox(fontName & " " & fontSize)
End If
End Sub
End Class

OPEN DIALOG BOX


The OpenFileDialog component displays a dialog box that allows the user to choose a file to
open.

The FileName property can be set prior to showing the dialog box. This causes the dialog box to
initially display the given filename. In most cases, your applications should set the
InitialDirectory, Filter, and FilterIndex properties prior to calling ShowDialog.
The following VB.Net program invites an OpenFile Dialog Box and retrieve the selected
filename to a string.
Source code

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim dlg As New OpenFileDialog
dlg.ShowDialog()
If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim fileName As String
fileName = dlg.FileName
MsgBox(fileName)
End If
End Sub
End Class

PRINT DIALOG BOX


The PrintDialog component displays a dialog box 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 Print dialog box includes a Print Range group of radio buttons that indicate whether the user
wants to print all pages, a range of pages, or only the selected text. The dialog box includes an
edit control in which the user can type the number of copies to print. The Print To File check box
indicates whether the user wants to send output to a file rather than to a printer. By default, the
Print dialog box initially displays information about the current default printer.

Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
Button1.Click
Dim dlg As New PrintDialog
dlg.ShowDialog()
End Sub
End Class

ARRAY LIST
ArrayList is one of the most flixible data structure from VB.NET Collections. ArrayList
contains a simple list of values and very easily we can add , insert , delete , view etc.. to do with
ArrayList. It is very flexible becuse we can add without any size information , that is it grow
dynamically and also shrink .
Important functions in ArrayList
Add : Add an Item in an ArrayList
Insert : Insert an Item in a specified position in an ArrayList
Remove : Remove an Item from ArrayList
RemoveAt: remeove an item from a specified position
Sort : Sort Items in an ArrayList
How to add an Item in an ArrayList ?
Syntax : ArrayList.add(Item)
Item : The Item to be add the ArrayList
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
How to Insert an Item in an ArrayList ?
Syntax : ArrayList.insert(index,item)
index : The position of the item in an ArrayList

Item : The Item to be add the ArrayList


ItemList.Insert(3, "item6")
How to remove an item from arrayList ?
Syntax : ArrayList.Remove(item)
Item : The Item to be add the ArrayList
ItemList.Remove("item2")
How to remove an item in a specified position from an ArrayList ?
Syntax : ArrayList.RemoveAt(index)
index : the position of an item to remove from an ArrayList
ItemList.RemoveAt(2)
How to sort ArrayList ?
Syntax : ArrayListSort()
The following VB.NET source code shows some function in ArrayList
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim ItemList As New ArrayList()
ItemList.Add("Item4")
ItemList.Add("Item5")
ItemList.Add("Item2")
ItemList.Add("Item1")
ItemList.Add("Item3")
MsgBox("Shows Added Items")
For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
'insert an item
ItemList.Insert(3, "Item6")
'sort itemms in an arraylist
ItemList.Sort()
'remove an item
ItemList.Remove("Item1")
'remove item from a specified index
ItemList.RemoveAt(3)

MsgBox("Shows final Items the ArrayList")


For i = 0 To ItemList.Count - 1
MsgBox(ItemList.Item(i))
Next
End Sub
End Class

Hash table
HashTable stores a Key Value pair type collection of data . We can retrive items from hashTable
to provide the key . Both key and value are Objects.
The common functions using in Hashtable are :
Add : To add a pair of value in HashTable
Syntax : HashTable.Add(Key,Value)
Key : The Key value
Value : The value of corrosponding key
ContainsKey : Check if a specified key exist or not
Synatx : HashTable.ContainsKey(key)
Key : The Key value for search in HahTable
ContainsValue : Check the specified Value exist in HashTable
Synatx : HashTable.ContainsValue(Value)
Value : Search the specified Value in HashTable
Remove : Remove the specified Key and corrosponding Value
Syntax : HashTable.Remove(Key)
Key : The argument key of deleting pairs
The following source code shows all important operations in a HashTable
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim weeks As New Hashtable

Dim day As DictionaryEntry


weeks.Add("1", "Sun")
weeks.Add("2", "Mon")
weeks.Add("3", "Tue")
weeks.Add("4", "Wed")
weeks.Add("5", "Thu")
weeks.Add("6", "Fri")
weeks.Add("7", "Sat")
'Display a single Item
MsgBox(weeks.Item("5"))
'Search an Item
If weeks.ContainsValue("Tue") Then
MsgBox("Find")
Else
MsgBox("Not find")
End If
'remove an Item
weeks.Remove("3")
'Display all key value pairs
For Each day In weeks
MsgBox(day.Key " -- " day.Value)
Next
End Sub
End Class

Stack
Stack is one of another easy to use VB.NET Collections . Stack follows the push-pop operations,
that is we can Push Items into Stack and Pop it later also it follows the Last In First Out (LIFO)
system. That is we can push the items into a stack and get it in reverse order. Stack returns the
last item first.
Commonly used methods :
Push : Add (Push) an item in the stack datastructure
Syntax : Stack.Push(Object)
Object : The item to be inserted.
Pop : Pop return the item last Item to insert in stack
Syntax : Stack.Pop()
Return : The last object in the Stack
Contains : Check the object contains in the stack
Syntax : Stack.Contains(Object)

Object : The specified Object to be seach


The following VB.NET Source code shows some of commonly used functions :
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim stackTable As New Stack
stackTable.Push("Sun")
stackTable.Push("Mon")
stackTable.Push("Tue")
stackTable.Push("Wed")
stackTable.Push("Thu")
stackTable.Push("Fri")
stackTable.Push("Sat")
If stackTable.Contains("Wed") Then
MsgBox(stackTable.Pop())
Else
MsgBox("not exist")
End If
End Sub
End Class

Queue
The Queue is another adtastructure from VB.NET Collections . Queue works like First In First
Out method and the item added first in the Queue is first get out from Queue. We can Enqueue
(add) items in Queue and we can Dequeue (remove from Queue ) or we can Peek (that is get the
reference of first item added in Queue ) the item from Queue.
The commonly using functions are follows :
Enqueue : Add an Item in Queue
Syntax : Stack.Enqueue(Object)
Object : The item to add in Queue
Dequeue : Remove the oldest item from Queue (we dont get the item later)
Syntax : Stack.Dequeue()
Returns : Remove the oldest item and return.
Peek : Get the reference of the oldest item (it is not removed permenantly)

Syntax : Stack.Peek()
returns : Get the reference of the oldest item in the Queue
The following VB.NET Source code shows some of commonly used functions :
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
Dim queueList As New Queue
queueList.Enqueue("Sun")
queueList.Enqueue("Mon")
queueList.Enqueue("Tue")
queueList.Enqueue("Wed")
queueList.Enqueue("Thu")
queueList.Enqueue("fri")
queueList.Enqueue("Sat")
MsgBox(queueList.Dequeue())
MsgBox(queueList.Peek())
If queueList.Contains("Sun") Then
MsgBox("Contains Sun ")
Else
MsgBox("Not Contains Sun ")
End If
End Sub
End Class

Array
Arrays are using for store similar data types grouping as a single unit. We can access Array
elements by its numeric index.
Dim week(6) As String
The above Vb.Net statements means that , an Array named as week declared as a String type and
it can have the capability of seven String type values.
week(0) = "Sunday"
week(1) = "Monday"
In the above statement , we initialize the values to the String Array. week(0) = "Sunday" means ,
we initialize the first value of Array as "Sunday" ,
Dim weekName as String = week(1)
We can access the Arrays elements by providing its numerical index, the above statement we
access the second value from the week Array.

In the following program , we declare an Array "week" capability of seven String values and
assigns the seven values as days in a week . Next step is to retrieve the elements of the Array
using a For loop. For finding the end of an Array we used the Length function of Array Object.
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim week(6) As String
week(0) = "Sunday"
week(1) = "Monday"
week(2) = "Tuesday"
week(3) = "Wednesday"
week(4) = "Thursday"
week(5) = "Friday"
week(6) = "Saturday"
For i = 0 To week.Length - 1
MsgBox(week(i))
Next
End Sub
End Class

Dynamic array
Dynamic Arrays can resize the capability of the Array at runtime .when you are in a situation
that you do not know exactly the number of elements to store in array while you making the
program. In that situations we are using Dynamic Array .
Initial declaration
Dim scores() As Integer
Resizing
ReDim scores(1)
If you want to keep the existing items in the Array , you can use the keyword Preserve .
ReDim Preserve scores(2)
In this case the Array dynamically allocate one more String value and keep the existing values.
Source code
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Button1.Click
Dim i As Integer
Dim scores() As Integer
ReDim scores(1)
scores(0) = 100
scores(1) = 200
For i = 0 To scores.Length - 1
MsgBox(scores(i))
Next
ReDim Preserve scores(2)
scores(2) = 300
For i = 0 To scores.Length - 1
MsgBox(scores(i))
Next
End Sub
End Class

Name and value collection


NameValueCollection is used to store data like Name, Value format. It is very similar to Vb.Net
HashTable, HashTable also stores data in Key , value format . NameValueCollection can hold
more than one value for a corresponding Key.
Adding new pairs
Add(ByVal name As String, ByVal value As String)
Add("High","80")
Get the value of corresponding Key
GetValues(ByVal name As String) As String()
String values() = GetValues("High")
Source code
Imports System.Collections.Specialized
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim markStatus As New NameValueCollection
Dim key As String

Dim values() As String


markStatus.Add("Very High", "80")
markStatus.Add("High", "60")
markStatus.Add("medium", "50")
markStatus.Add("Pass", "40")
For Each key In markStatus.Keys
values = markStatus.GetValues(key)
For Each value As String In values
MsgBox(key & " - " & value)
Next value
Next key
End Sub
End Class

String length
The Length() function in String Class returned the number of characters occurred in a String.
System.String.Length() As Integer
Returns:
Integer : The number of characters in the specified String
For ex:
"This is a Test".Length() returns 14.
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "This is a Test"
MsgBox(str.Length())
End Sub
End Class

String insert
The Insert() function in String Class will insert a String in a specified index in the String
instance.
System.String.Insert(Integer ind, String str) as String

Parameters:
ind - The index of the specified string to be inserted.
str - The string to be inserted.
Returns:
String - The result string.
Exceptions:
System.ArgumentOutOfRangeException: startIndex is negative or greater than the length of this
instance
System.ArgumentNullException : If the argument is null.
For ex:
"This is Test".Insert(8,"Insert ") returns "This is Insert Test"
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = "This is VB.NET Test"
Dim insStr As String = "Insert "
Dim strRes As String = str.Insert(15, insStr)
MsgBox(strRes)
End Sub
End Class

String index of
The IndexOf method in String Class returns the index of the first occurrence of the specified
substring.
System.String.IndexOf(String str) As Integer
Parameters:
str - The parameter string to check its occurrences
Returns:
Integer - If the parameter String occurred as a substring in the specified String

it returns position of the first character of the substring .


If it does not occur as a substring, -1 is returned.
Exceptions:
System.ArgumentNullException: If the Argument is null.
For ex:
"This is a test".IndexOf("Test") returns 10
"This is a test".IndexOf("vb") returns -1
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "VB.NET TOP 10 BOOKS"
MsgBox(str.IndexOf("BOOKS"))
End Sub
End Class

String format
VB.NET String Format method replace the argument Object into a text equivalent
System.Striing.
System.Format(ByVal format As String, ByVal arg0 As Object) As String
Parameters:
String format : The format String
The format String Syntax is like {indexNumber:formatCharacter}
Object arg0 : The object to be formatted.
Returns:
String : The formatted String
Exceptions:

System.ArgumentNullException : The format String is null.


System.FormatException : The format item in format is invalid.
The number indicating an argument to format is less than zero, or greater than or equal to the
number of specified objects to format.
For ex :
Currency :
String.Format("{0:c}", 10) will return $10.00
The currency symbol ($) displayed depends on the global locale settings.
Date :
String.Format("Today's date is {0:D}", DateTime.Now)
You will get Today's date like : 01 January 2005
Time :
String.Format("The current time is {0:T}", DateTime.Now)
You will get Current Time Like : 10:10:12
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim dNum As Double
dNum = 32.123456789
MsgBox("Formated String " & String.Format("{0:n4}", dNum))
End Sub
End Class

String equals
VB.NET String Equals function is to check the specified two String Object values are same or
not
System.String.Equals(String str1, String str2) As Boolean
Parameters:

String str1 : The String argument


String str2 : The String argument
Returns:
Boolean : Yes/No
It return the values of the two String Objects are same
For ex :
Str1 = "Equals()"
Str2 = "Equals()"
String.Equals(Str1,Str2) returns True
String.Equals(Str1.ToLower,Str2) returns False
Because the String Objects values are different
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str1 As String = "Equals"
Dim str2 As String = "Equals"
If String.Equals(str1, str2) Then
MsgBox("Strings are Equal() ")
Else
MsgBox("Strings are not Equal() ")
End If
End Sub
End Class

String copy to
VB.NET String CopyTo method Copies a specified number of characters from a specified
position in this instance to a specified position in an array of characters.
System.String.CopyTo(ByVal sourceIndex As Integer, ByVal destination() As Char, ByVal
destinationIndex As Integer, ByVal count As Integer)
Parameters:

Integer sourceIndex : The starting position of the source String


Char destination() : The character Array
Integer destinationIndex : Array element in the destination
Integer count : The number of characters to destination
Exceptions:
System.ArgumentNullException : If the destination is null
System.ArgumentOutOfRangeException :
Source Index, DestinationIndes or Count is a -ve value
Count is greater than the length of the substring from startIndex to the end of this instance
count is greater than the length of the subarray from destinationIndex to the end of destination
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str1 As String = "CopyTo() sample"
Dim chrs(5) As Char
str1.CopyTo(0, chrs, 0, 6)
MsgBox(chrs(0) + chrs(1) + chrs(2) + chrs(3) + chrs(4) + chrs(5))
End Sub
End Class

String copy
VB.NET String Copy method is create a new String object with the same content
System.String.Copy(ByVal str As String) As String
Parameters:
String str : The argument String for Copy method
Returns:
String : Returns a new String as the same content of argument String

Exceptions:
System.ArgumentNullException : If the argument is null.
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str1 As String
Dim str2 As String
str1 = "VB.NET Copy() test"
str2 = String.Copy(str1)
MsgBox(str2)
End Sub
End Class

String contains
The Contains method in the VB.NET String Class check the specified parameter String exist in
the String
System.String.Contains(String str) As Boolean
Parameters:
String str - input String for search
Returns:
Boolean - Yes/No
If the str Contains in the String then it returns true
If the str does not Contains in the String it returns False
For ex: "This is a Test".Contains("is") return True
"This is a Test".Contains("yes") return False
Exceptions:
System.ArgumentNullException : If the argument is null

Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "VB.NET TOP 10 BOOKS"
If str.Contains("TOP") = True Then
MsgBox("The string Contains() 'TOP' ")
Else
MsgBox("The String does not Contains() 'TOP'")
End If
End Sub
End Class

String compare
The VB.NET String Compare function is use to compare two String Objects.
System.String.Compare(String str1,String str2, Boolean ) As Integer
It returns an Integer indication lexical relationship between the two comprehends
Parameters:
String str1 : Parameter String
String str2 : Parameter String
Boolean True/False Indication to check the String with case sensitive or without case sensitive
Returns:
Integer : returns less than zero, zero or greater than zero.
Less than zero : str1 is less than str2
zero : str1 is equal to str2
Greater than zero : str1 is grater than str2
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str1 As String
Dim str2 As String

str1 = "vb.net"
str2 = "VB.NET"
Dim result As Integer
result = String.Compare(str1, str2)
MsgBox(result)
result = String.Compare(str1, str2, True)
MsgBox(result)
End Sub
End Class

String clone
The VB.NET String Clone() method returns a reference to this instance of String.
Public Function Clone() As Object
Returns:
Object : Return the instance of the String
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = "Clone() Test"
Dim clonedString As String
clonedString = str.Clone()
MsgBox(clonedString)
End Sub
End Class

When you run this program you ill get the same content of the first string "Clone() Test"
String chars
The VB.NET String Chars method return the character at the specified index of an instance
System.String.Chars(ByVal index As Integer) As Char
Parameters:
Integer index - The character position in the returned Character.
Returns:

Char - The return Character.


For ex :
"Return test".Chars(3) return a single character 'u'
If u pass a number more than String length will return an exception
"Return test".Chars(25) will throw a System.IndexOutOfRangeException
Exceptions:
System.IndexOutOfRangeException : The index is less than zero or greater than the length of
String Object
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String = "Returned Character Chars()"
Dim singleChar As Char
singleChar = str.Chars(3)
MsgBox(singleChar)
End Sub
End Class

When you run this source code you will return a messagebox show 'u'

Sub string

Substring in Vb.Net String Class returns a new string that is a substring of this string. The
substring begins at the specified given index and extended up to the given length.
Public Function Substring(ByVal startIndex As Integer, ByVal length As Integer) As String
Parameters:
startIndex: The index of the start of the substring.
length: The number of characters in the substring.
Returns:

The specified substring.


Exceptions:
System.ArgumentOutOfRangeException : the beginIndex or length less than zero, or the begin
index + length not within the specified string
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim retString As String
str = "This is substring test"
retString = str.Substring(8, 9)
MsgBox(retString)
End Sub
End Class

When you execute this program , its will display "subtring" in the messagebox.
String split
Vb.Net String Split function returns an array of String containing the substrings delimited by
the given System.Char array.
Public Function Split(ByVal ParamArray separator() As Char) As String()
Parameters:
separator - the given delimiter
Returns:
An array of Strings delimited by one or more characters in separator
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim strArr() As String
Dim count As Integer
str = "vb.net split test"

strArr = str.Split(" ")


For count = 0 To strArr.Length - 1
MsgBox(strArr(count))
Next
End Sub
End Class

When you execute this programme , you will get "vb.net" "split" "test" in separate messagebox
End with
EndsWith in VB.NET String Class check if the Parameter String EndsWith the Specified String
System.String.EndsWith(String suffix) as Boolean
Parameters:
suffix - The passing String for it EndsWith
Returns:
Boolean - Yes/No
If the String EndsWith the Parameter String it returns True
If the String doesnt EndsWith the Parameter String it return False
For ex : "This is a Test".EndsWith("Test") returns True
"This is a Test".EndsWith("is") returns False
Exceptions:
System.ArgumentNullException : If the argument is null
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
str = "VB.NET TOP 10 BOOKS"
If str.EndsWith("BOOKS") = True Then
MsgBox("The String EndsWith 'BOOKS' ")
Else
MsgBox("The String does not EndsWith 'BOOKS'")

End If
End Sub
End Class

When you execute the program you will get a message box like "The String EndsWith 'BOOKS'
"
String concat
Concat in VB.NET String Class using for concat two specified String Object
System.String.Concat(ByVal str1 As String, ByVal str2 As String) As String
String Concat method returns a new String
Parameters:
String str1 : Parameter String
String str2 : Parameter String
Returns:
String : A new String retrun with str1 Concat with str2
Source code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim str1 As String
Dim str2 As String
str1 = "Concat() "
str2 = "Test"
MsgBox(String.Concat(str1, str2))
End Sub
End Clas

When you run this source code you will get "Concat() Test " in message box.
Directory operation

Using 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.
How to create a directory ?
In order to create a new directory , we can call CreateDirectory directly from Directory class.
Syntax : Directory.CreateDirectory(DirPath)
DirPath : The name of the new directory
VB.NET : Directory.CreateDirectory("c:\testdir")
How to check a directory exist or not ?
Before we creating a directory , we usually check that directory exist or not. For that we are
using the Exists method in the Directory class.
Syntax : Directory.Exists(DirPath) as Boolean
DirPath : The name of the directory
Boolean : Returns true or false , if directory exist it Returns true , else it Returns false
VB.NET : Directory.Exists("c:\testdir")
How to move a Directory ?
If we want to move a directory and its contents from one location to another , we can use the
Move method in the Directory class.
Syntax : Move(sourceDirName,destDirName)
sourceDirName : The source directory we want to move.
destDirName : The destinations directory name.
VB.NET : Directory.Move("c:\testdir1\testdir2", "c:\testdir")
How to delete a Directory ?
When we want to delete a directory we can use the Delete method in the Directory class
Syntax : Delete(DirPath)

DirPath : The Directory we want to delete.


VB.NET : Directory.Delete("c:\testdir1")
The following VB.NET source code shows these operations :
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
If Directory.Exists("c:\testDir1") Then
'shows message if testdir1 exist
MsgBox("Directory 'testDir' Exist ")
Else
'create the directory testDir1
Directory.CreateDirectory("c:\testDir1")
MsgBox("testDir1 created ! ")
'create the directory testDir2
Directory.CreateDirectory("c:\testDir1\testDir2")
MsgBox("testDir2 created ! ")
'move the directory testDir2 as testDir in c:
Directory.Move("c:\testDir1\testDir2", "c:\testDir")
MsgBox("testDir2 moved ")
'delete the directory testDir1
Directory.Delete("c:\testDir1")
MsgBox("testDir1 deleted ")
End If
End Sub
End Class

File operation
File class is using for the File operations in VB.NET. We can create , delete , copy etc. operations
do with File class.
How to create a File ?
In order to create a new File , we can call Create method in the File class.
Syntax : File.Create(FilePath)
FilePath : The name of the new File Object
File.Create("c:\testFile.txt")
How to check a File exist or not ?

Before we creating a File object , we usually check that File exist or not. For that we are using
the Exists method in the File class.
Syntax : File.Exists(FilePath) as Boolean
FilePath : The name of the File
Boolean : Returns true or false , if File exist it Returns true else Returns false
VB.NET : File.Exists("c:\testFile.txt")
The following VB.NET source code shows these operations :
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If File.Exists("c:\testFile.txt") Then
'shows message if testFile exist
MsgBox("File 'testFile' Exist ")
Else
'create the file testFile.txt
File.Create("c:\testFile.txt")
MsgBox("File 'testFile' created ")
End If
End Sub
End Class

When you execute this source code , it first check the File exist or not , If exist it shows message
file exist , else it create a new File Object .
How to Copy a File ?
If we want the Copy of the File Object we can use the Copy method in File class.
Syntax : Copy(sourceFileName, destFileName)
sourceFileName : The source file we want to move.
destFileName : The destinations file name.
VB.NET : File.Copy("c:\testFile.txt", "c:\testDir\testFile.txt")
How to delete a File Object ?
When we want to delete a File Object we can use the Delete methods in the File class
Syntax : Delete(FilePath)

DirPath : The File Object you want to delete.


VB.NET : File.Delete("c:\testDir\testFile.txt")
The following VB.NET source code shows these operations :
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
If Not File.Exists("c:\testFile.txt") Then
MsgBox("FIle not exist ")
Else
File.Copy("c:\testFile.txt", "c:\testDir\testFile.txt")
MsgBox("File Copied ")
File.Delete("c:\testFile.txt")
MsgBox("file deleted ")
End If
End Sub
End Class

File stream
The FileStream Class represents a File in the Computer. FileStream allows to move data to and
from the stream as arrays of bytes. We operate File using FileMode in FileStream Class
Some of FileModes as Follows :
FileMode.Append : Open and append to a file , if the file does not exist , it create a new file
FileMode.Create : Create a new file , if the file exist it will append to it
FileMode.CreateNew : Create a new File , if the file exist , it throws exception
FileMode.Open : Open an existing file
How to create a file using VB.NET FileStream ?
The following example shows , how to write in a file using FileStream.
Source code
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click


Try
Dim wFile As System.IO.FileStream
Dim byteData() As Byte
byteData = Encoding.ASCII.GetBytes("FileStream Test1")
wFile = New FileStream("streamtest.txt", FileMode.Append)
wFile.Write(byteData, 0, byteData.Length)
wFile.Close()
Catch ex As IOException
MsgBox(ex.ToString)
End Try
End Sub
End Class

When we execute the program , it create a new File and write the content to it .
Text reader
Textreader and TextWriter are the another way to read and write file respectively, even though
these are not stream classes. The StreamReader and StreamWriter classes are derived from
TextReader and TextWriter classes respectively.
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim line As String
Dim readFile As System.IO.TextReader = New _
StreamReader("C:\TextReader.txt")
While True
line = readFile.ReadLine()
If line Is Nothing Then
Exit While
Else
MsgBox(line)
End If
End While
readFile.Close()
readFile = Nothing
Catch ex As IOException
MsgBox(ex.ToString)
End Try
End Sub
End Class

When you execute this program the TextReader read the file line by line.
Simple text reader

Textreader and TextWriter are the another way to read and write file respectively, even though
these are not stream classes. The StreamReader and StreamWriter classes are derived from
TextReader and TextWriter classes respectively. The following program using TextReader ,
Read the entire content of the file into a String
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim line As String
Dim readFile As System.IO.TextReader = New _
StreamReader("C:\Test1.txt")
line = readFile.ReadToEnd()
MsgBox(line)
readFile.Close()
readFile = Nothing
Catch ex As IOException
MsgBox(ex.ToString)
End Try
End Sub
End Class

When you execute this program , TextReader read the entire file in one stretch.
Text writer
Textreader and TextWriter are the another way to read and write file respectively, even though
these are not stream classes. The StreamReader and StreamWriter classes are derived from
TextReader and TextWriter classes respectively. The following sample source showing how
write in a file using TextWriter .
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim writeFile As System.IO.TextWriter = New _
StreamWriter("c:\textwriter.txt")
writeFile.WriteLine("vb.net-informations.com")
writeFile.Flush()
writeFile.Close()
writeFile = Nothing
Catch ex As IOException
MsgBox(ex.ToString)
End Try
End Sub
End Class

When you execute this source code , you will get a file TextWriter.txt and inside it written
vb.net-informations.com
Binary reader
BinaryReader Object works at lower level of Streams. BinaryReader is used for read premitive
types as binary values in a specific encoding stream. Binaryreader Object works with Stream
Objects that provide access to the underlying bytes. For creating a BinaryReader Object , you
have to first create a FileStream Object and then pass BinaryReader to the constructor method .
Dim readStream As FileStream
readStream = New FileStream("c:\testBinary.dat", FileMode.Open)
Dim readBinary As New BinaryReader(readStream)
The main advantages of Binary information is that stores files as Binary format is the best
practice of space utilization.
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim readStream As FileStream
Dim msg As String
Try
readStream = New FileStream("c:\testBinary.dat", FileMode.Open)
Dim readBinary As New BinaryReader(readStream)
msg = readBinary.ReadString()
MsgBox(msg)
readStream.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

BinaryWriter you can use in the same way to write as binary.


Binary writer
The BinaryWriter Object works at lower level of Streams. BinaryWriter is used for write
premitive types as binary values in a specific encoding stream. BinaryWriter Object works with
Stream Objects that provide access to the underlying bytes. For creating a BinaryWriter Object ,

you have to first create a FileStream Object and then pass BinaryWriter to the constructor
method .
Dim writeStream As FileStream
writeStream = New FileStream("c:\testBinary.dat", FileMode.Create)
Dim writeBinay As New BinaryWriter(writeStream)
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 utilization.
Source code
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim writeStream As FileStream
Try
writeStream = New FileStream("c:\testBinary.dat", FileMode.Create)
Dim writeBinay As New BinaryWriter(writeStream)
writeBinay.Write("This is a test for BinaryWriter !")
writeBinay.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

BinaryReader you can use in the same way to read as binary.


Xmp and bmp file

XPS is an xml markup format that represents a page's content in Windows Presentation
Foundation vector format. The XPS Document Writer allows you to create .xps files using any
program that you run on Windows. XPS documents look 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 XPS
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 xps document to a bitmap image. Create a new
VB.NET project and add a Button to Form and add the following references to your project.
Go to Project->Add References 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.Packaging
Imports System.Windows.Documents
Imports System.Windows.Xps.Packaging
Imports System.Windows.Media.Imaging
Imports System.Collections.Generic
Imports System.Windows.Forms
Imports System.Text
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Try
Dim xpsFile As String = "c:\Completed-Form.xps"
xpsToBmp(xpsFile)
MessageBox.Show("Done")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Public Shared Sub xpsToBmp(ByVal xpsFile As String)
Dim xps As New XpsDocument(xpsFile, System.IO.FileAccess.Read)
Dim sequence As FixedDocumentSequence = xps.GetFixedDocumentSequence()
1

For pageCount As Integer = 0 To sequence.DocumentPaginator.PageCount -

Dim page As DocumentPage =


sequence.DocumentPaginator.GetPage(pageCount)
Dim toBitmap As New RenderTargetBitmap(CInt(page.Size.Width),
CInt(page.Size.Height), 96, 96, System.Windows.Media.PixelFormats.[Default])
toBitmap.Render(page.Visual)
Dim bmpEncoder As BitmapEncoder = New BmpBitmapEncoder()
bmpEncoder.Frames.Add(BitmapFrame.Create(toBitmap))
Dim fStream As New FileStream("c:\xpstobmp" & pageCount & ".bmp",
FileMode.Create, FileAccess.Write)
bmpEncoder.Save(fStream)
fStream.Close()
Next
End Sub
End Class

How to create an excel


From the following sections you can find how to create an Excel 2007 worksheet through
VB.NET 2005. For creating an Excel 2007 worksheet in VB.NET 2005 , you have to add the
Microsoft Excel 12.0 Object Library in you project.
From the following pictures to show how to add Excel reference library in your project.
1. Create a new project and add a button to the Form.
Select reference dialouge from Project menu

Select Microsoft Excel 12.0 Object Library and click OK button

Now you can start coding to create a new Excel file.


Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 1) = "http://vb.net-informations.com"
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)

releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created , you can find the file c:\")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

How to open or read


The following sections you can find how to open and edit an Excel 2007 worksheet through
VB.NET 2005. For open or edit an Excel 2007 worksheet in VB.NET 2005 , you have to add the
Microsoft Excel 12.0 Object Library in you project.
From the following pictures to show how to add Excel reference library in your project.
1. Create a new project and add a button to the Form.
Select reference dialouge from Project menu

Select Microsoft Excel 12.0 Object Library and click OK button

Now you can start coding to open or read from Excel file and edit cells.
Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open("c:\test1.xlsx")
xlWorkSheet = xlWorkBook.Worksheets("sheet1")
'display the cells value B2
MsgBox(xlWorkSheet.Cells(2, 2).value)
'edit the cell with new value
xlWorkSheet.Cells(2, 2) = "http://vb.net-informations.com"
xlWorkBook.Close()
xlApp.Quit()

releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

In the code , Imports Excel = Microsoft.Office.Interop.Excel - we assign the excel reference


to
a
vatriable
Excel.
When you execute this program , the program open the file c:\test1.xlsx and edit the content in
the cell B2, it replace the old content to "http://vb.net-informations.com" . Before running this
program you have to create an excel file name test1.xlsx and add some data in the cell B2.
How to read entire worksheet in an Excel workbook
In the following section you can see How to find the last row data in Excel worksheet or How to
find the Used area in a worksheet. For finding last row we are using WorkSheet.UsedRange . It
will return the last cell . The follwoing code open an Excel file and read the entire content.
Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim
Dim
Dim
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
range As Excel.Range
rCnt As Integer
cCnt As Integer
Obj As Object

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Open("c:\vbexcel.xlsx")
xlWorkSheet = xlWorkBook.Worksheets("sheet1")
range = xlWorkSheet.UsedRange

For rCnt = 1 To range.Rows.Count


For cCnt = 1 To range.Columns.Count
Obj = CType(range.Cells(rCnt, cCnt), Excel.Range)
MsgBox(Obj.value)
Next
Next
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

When you execute this source code the program read all content from Excel file.
How to Format Excel 2007 Page in VB.NET
The following sections you can see , how to do the commonly used format in Excel 2007 page.
Here we enter the data of a Mark List and format the page. First we MERGE excel cell and
create the heading , then the students name and totals make as BOLD . And finally create a
border for the whole marklist part.
After you run the source code you will get an Excel file its look like in the following picture .

Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value
chartRange As Excel.Range

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'add data
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,

2)
3)
4)
5)

=
=
=
=

""
"Student1"
"Student2"
"Student3"

xlWorkSheet.Cells(5, 2) = "Term1"
xlWorkSheet.Cells(5, 3) = "80"

xlWorkSheet.Cells(5, 4) = "65"
xlWorkSheet.Cells(5, 5) = "45"
xlWorkSheet.Cells(6,
xlWorkSheet.Cells(6,
xlWorkSheet.Cells(6,
xlWorkSheet.Cells(6,

2)
3)
4)
5)

=
=
=
=

"Term2"
"78"
"72"
"60"

xlWorkSheet.Cells(7,
xlWorkSheet.Cells(7,
xlWorkSheet.Cells(7,
xlWorkSheet.Cells(7,

2)
3)
4)
5)

=
=
=
=

"Term3"
"82"
"80"
"65"

xlWorkSheet.Cells(8,
xlWorkSheet.Cells(8,
xlWorkSheet.Cells(8,
xlWorkSheet.Cells(8,

2)
3)
4)
5)

=
=
=
=

"Term4"
"75"
"82"
"68"

xlWorkSheet.Cells(9,
xlWorkSheet.Cells(9,
xlWorkSheet.Cells(9,
xlWorkSheet.Cells(9,

2)
3)
4)
5)

=
=
=
=

"Total"
"315"
"299"
"238"

chartRange = xlWorkSheet.Range("b2", "e3")


chartRange.Merge()
chartRange.FormulaR1C1 = "MARK LIST"
chartRange.HorizontalAlignment = 3
chartRange.VerticalAlignment = 3
chartRange = xlWorkSheet.Range("b4", "e4")
chartRange.Font.Bold = True
chartRange = xlWorkSheet.Range("b9", "e9")
chartRange.Font.Bold = True
chartRange = xlWorkSheet.Range("b2", "e9")
chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, _
Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex. _
xlColorIndexAutomatic,Excel.XlColorIndex.xlColorIndexAutomatic)
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("File created !")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing

Finally
GC.Collect()
End Try
End Sub
End Class

How to insert a Picture in Excel 2007 through programing on VB.NET 2005


The following VB.NET program shows , how to insert a picture in Excel 2007 . For inserting a
picture in Excel 2007 we hav to call the AddPicture method. For that you have to specify
PictureName with path , Left , Top , Width and Height.

Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)

xlWorkSheet = xlWorkBook.Sheets("sheet1")
'add some text
xlWorkSheet.Cells(1, 1) = "http://vb.net-informations.com"
xlWorkSheet.Cells(2, 1) = "Adding picture in Excel File"
'replace you picture to xl_pic.JPG
xlWorkSheet.Shapes.AddPicture("C:\xl_pic.JPG", _
Microsoft.Office.Core.MsoTriState.msoFalse, _
Microsoft.Office.Core.MsoTriState.msoCTrue, 50, 50, 300, 45)
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created , you can find the file c:\")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

When you execute this program , you will get an Excel file (C:\vbexcel.xlsx) with insert the
picture.
How to insert a background Picture in Excel 2007 through VB.NET 2005

The following VB.NET program shows , how to insert a background picture in Excel 2007 . For
inserting a background picture in Excel 2007 we hav to call the SetBackgroundPicture mthod in
worksheet .
Syntax : SetBackgroundPicture(ByVal Filename As String)
Filename : The background picture filename .

Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'set back ground
'replace your background picture to xl_pic.JPG
xlWorkSheet.SetBackgroundPicture("C:\xl_pic.JPG")
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)

MsgBox("Excel file created , you can find the file c:\")


End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

When you execute this program , you will get an Excel file (C:\vbexcel.xlsx) with insert
background picture.
How to create a Chart in Excel 2007 in VB.NET
We can create Chart in Excel using VB.NET 2005 . The following section shows how to create
a Chart in Excel 2007 through VB.NET source code .
Before we crate a Chart , we have to fill data in Excel sheet. After enter data your Excel sheet is
look like the following picture.

After fill the data , We have to create a chart object in VB.NET and configure the Chart object
with necressary data like positions , size , data range , chart type etc..
The following picture shows the excel file after created a chart.

Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet

Dim misValue As Object = System.Reflection.Missing.Value


xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'add data
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,

1)
2)
3)
4)

=
=
=
=

""
"Student1"
"Student2"
"Student3"

xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,

1)
2)
3)
4)

=
=
=
=

"Term1"
"80"
"65"
"45"

xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,

1)
2)
3)
4)

=
=
=
=

"Term2"
"78"
"72"
"60"

xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,

1)
2)
3)
4)

=
=
=
=

"Term3"
"82"
"80"
"65"

xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,

1)
2)
3)
4)

=
=
=
=

"Term4"
"75"
"82"
"68"

'create chart
Dim chartPage As Excel.Chart
Dim xlCharts As Excel.ChartObjects
Dim myChart As Excel.ChartObject
Dim chartRange As Excel.Range
xlCharts = xlWorkSheet.ChartObjects
myChart = xlCharts.Add(10, 80, 300, 250)
chartPage = myChart.Chart
chartRange = xlWorkSheet.Range("A1", "d5")
chartPage.SetSourceData(Source:=chartRange)
chartPage.ChartType = Excel.XlChartType.xlColumnClustered
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created , you can find the file c:\")
End Sub
Private Sub releaseObject(ByVal obj As Object)

Try

System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

When you execute this program you will get the Excel file with Chart.
How to export a Chart in Excel 2007 as Picture file from VB.NET
The follwoing program shows how can Export a Chart from Excel 2007 to Picture file like ,
BMP , JPG , GIF etc .Before we crate a Chart , we have to fill data in Excel sheet. After enter
data your Excel sheet is look like the following picture.

After fill the data , We have to create a chart object in VB.NET and configure the Chart object
with necressary data like positions , size , data range , chart type etc.. and use the command for
export chart as picture file
The following picture shows the BMP file export from Excel.

Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'add data
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,

1)
2)
3)
4)

=
=
=
=

""
"Student1"
"Student2"
"Student3"

xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,

1)
2)
3)
4)

=
=
=
=

"Term1"
"80"
"65"
"45"

xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,

1)
2)
3)
4)

=
=
=
=

"Term2"
"78"
"72"
"60"

xlWorkSheet.Cells(4, 1) = "Term3"

xlWorkSheet.Cells(4, 2) = "82"
xlWorkSheet.Cells(4, 3) = "80"
xlWorkSheet.Cells(4, 4) = "65"
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,

1)
2)
3)
4)

=
=
=
=

"Term4"
"75"
"82"
"68"

'create chart
Dim chartPage As Excel.Chart
Dim xlCharts As Excel.ChartObjects
Dim myChart As Excel.ChartObject
Dim chartRange As Excel.Range
xlCharts = xlWorkSheet.ChartObjects
myChart = xlCharts.Add(10, 80, 300, 250)
chartPage = myChart.Chart
chartRange = xlWorkSheet.Range("A1", "d5")
chartPage.SetSourceData(Source:=chartRange)
chartPage.ChartType = Excel.XlChartType.xlColumnClustered
'exporting chart as picture file
xlWorkSheet.ChartObjects(1).chart.Export(FileName:= _
"C:\excel_chart_export.bmp", FilterName:="BMP")
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Chart File Exported !")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

When you execute this program you will get the picture file export from Excel file .
How to Excel 2007 Chart in VB.NET Picture Box

The follwoing program shows , how to get the Excel chart as an image in Picture Box .Before
we crate a Chart , we have to fill data in Excel sheet. After enter data your Excel sheet is look
like the following picture.

After fill the data , We have to create a chart object in VB.NET and configure the Chart object
with necressary data like positions , size , data range , chart type etc.. and use the command for
export chart as picture file , then load the picture from the path to picture box
The following picture shows the program screen after drawing the picture

Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'add data
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,
xlWorkSheet.Cells(1,

1)
2)
3)
4)

=
=
=
=

""
"Student1"
"Student2"
"Student3"

xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,
xlWorkSheet.Cells(2,

1)
2)
3)
4)

=
=
=
=

"Term1"
"80"
"65"
"45"

xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,
xlWorkSheet.Cells(3,

1)
2)
3)
4)

=
=
=
=

"Term2"
"78"
"72"
"60"

xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,

1)
2)
3)
4)

=
=
=
=

"Term3"
"82"
"80"
"65"

xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,

1)
2)
3)
4)

=
=
=
=

"Term4"
"75"
"82"
"68"

'create chart
Dim chartPage As Excel.Chart
Dim xlCharts As Excel.ChartObjects
Dim myChart As Excel.ChartObject
Dim chartRange As Excel.Range
xlCharts = xlWorkSheet.ChartObjects
myChart = xlCharts.Add(10, 80, 300, 250)
chartPage = myChart.Chart
chartRange = xlWorkSheet.Range("A1", "d5")
chartPage.SetSourceData(Source:=chartRange)
chartPage.ChartType = Excel.XlChartType.xlColumnClustered
'exporting chart as picture file
xlWorkSheet.ChartObjects(1).chart.Export(FileName:= _
"C:\excel_chart_export.bmp", FilterName:="BMP")
'load the pipcture into the picture box
PictureBox1.Image = New System.Drawing.Bitmap _
("C:\excel_chart_export.bmp")
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Chart File Exported !")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try

End Sub
End Class

When you execute this program you will get the picture in Picture Box from Excel Chart .
How to Excel 2007 DataBar in VB.NET

The following program shows , how to do the frequenly used format in Excel 2007 page. Here
we enter the data of a Mark List and format the page. First we MERGE excel cell and create the
heading , then the students name and totals make as BOLD and create a border for the whole
marklist part. Finally we select the range we want to add DataBar and select the color
After you run the source code you will get an Excel file its look like in the following picture .

Imports Excel = Microsoft.Office.Interop.Excel


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook

Dim xlWorkSheet As Excel.Worksheet


Dim misValue As Object = System.Reflection.Missing.Value
Dim chartRange As Excel.Range
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
'add data
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,
xlWorkSheet.Cells(4,

2)
3)
4)
5)

=
=
=
=

""
"Student1"
"Student2"
"Student3"

xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,
xlWorkSheet.Cells(5,

2)
3)
4)
5)

=
=
=
=

"Term1"
"10"
"65"
"45"

xlWorkSheet.Cells(6,
xlWorkSheet.Cells(6,
xlWorkSheet.Cells(6,
xlWorkSheet.Cells(6,

2)
3)
4)
5)

=
=
=
=

"Term2"
"78"
"72"
"60"

xlWorkSheet.Cells(7,
xlWorkSheet.Cells(7,
xlWorkSheet.Cells(7,
xlWorkSheet.Cells(7,

2)
3)
4)
5)

=
=
=
=

"Term3"
"82"
"80"
"65"

xlWorkSheet.Cells(8,
xlWorkSheet.Cells(8,
xlWorkSheet.Cells(8,
xlWorkSheet.Cells(8,

2)
3)
4)
5)

=
=
=
=

"Term4"
"75"
"82"
"98"

xlWorkSheet.Cells(9,
xlWorkSheet.Cells(9,
xlWorkSheet.Cells(9,
xlWorkSheet.Cells(9,

2)
3)
4)
5)

=
=
=
=

"Total"
"315"
"299"
"238"

chartRange = xlWorkSheet.Range("b2", "e3")


chartRange.Merge()
chartRange.FormulaR1C1 = "MARK LIST"
chartRange.HorizontalAlignment = 3
chartRange.VerticalAlignment = 3
chartRange = xlWorkSheet.Range("b4", "e4")
chartRange.Font.Bold = True
chartRange = xlWorkSheet.Range("b9", "e9")
chartRange.Font.Bold = True
chartRange = xlWorkSheet.Range("b2", "e9")
chartRange.BorderAround(Excel.XlLineStyle.xlContinuous, _
Excel.XlBorderWeight.xlMedium, Excel.XlColorIndex. _
ColorIndexAutomatic,Excel.XlColorIndex.xlColorIndexAutomatic)
chartRange = xlWorkSheet.Range("c5", "e9")
chartRange.FormatConditions.AddDatabar()

chartRange.FormatConditions(chartRange.FormatConditions.Count) _
.ShowValue = True
chartRange.FormatConditions(chartRange.FormatConditions.Count). _
SetFirstPriority()
chartRange.FormatConditions(1).BarColor.color = 8061142
chartRange.FormatConditions(1).BarColor.TintAndShade = 0
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("File created !")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

When you execute this program you will get a MarkList with databar
How to Excel 2007 Data Validation Input Message
Data Validation Input Messages is using to embed a message in cells in an Excel Spread Sheet.
When we select that cell the message will display . It 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 Messages in Excel .
The follwong image shows how a Data Validation Input Message after embedded in an Excel
cell.

Source code
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value
rangeCells As Excel.Range

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Range("B5", "D5").Validation.Add( _
Type:=Excel.XlDVType.xlValidateInputOnly, _
AlertStyle:=Excel.XlDVAlertStyle.xlValidAlertStop, _
Operator:=Excel.XlFormatConditionOperator.xlBetween)
xlWorkSheet.Range("B5", "D5").Validation.IgnoreBlank = True
xlWorkSheet.Range("B5", "B5").FormulaR1C1 = "Click Here " + _
"to see Notes"
xlWorkSheet.Range("B5", "D5").Validation.InputTitle = _
"vb.net-informations.com"

xlWorkSheet.Range("B5", "D5").Validation.ErrorTitle = "Error in Title"


xlWorkSheet.Range("B5", "D5").Validation.InputMessage = "Here is " + _
" the notes embeded - you can enter 255 characters maximum in notes "
xlWorkSheet.Range("B5", "D5").Validation.ErrorMessage = "Error in
Notes"

xlWorkSheet.Range("B5", "D5").Validation.ShowInput = True


xlWorkSheet.Range("B5", "D5").Validation.ShowError = True
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)

MsgBox("File created !")


End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

When you execute this source code you can find Input message in Cell.
How to read data from excel using OLEDB
Without using Excel Object we can insert , edit , delete , select etc. in cell content of an Excel
2007 file using OLEDB in VB.NET 2005 . Here we are using OleDbConnection ,
OleDbDataAdapter , DataSet for doing these operations in an Excel file. You have to import
System.Data in the project for doing these operations . For read the content from Excel file using
ado.net , We can use the SELECT command like in SQL Operations.
sample Select sql
sql = "select * from [Sheet1$]"
Here is the sample Excel file .

Open the connection using OLEDB Provider


(provider=Microsoft.Jet.OLEDB.4.0;Data Source='Your Filename';Extended
Properties=Excel 8.0;)
Specify which data you want to read
select * from [Sheet1$]
Here is the screen short after reading from Excel file .

Source code
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection _
("provider=Microsoft.Jet.OLEDB.4.0;" _
" Data Source='c:\testfile.xls'; " _
"Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter _
("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "TestTable")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

When you execute this program you will get the contents in the excel file to the DataGrid.
How to insert cell data in an Excel file using OLEDB

Without using Excel Object we can insert , edit , delete , select etc. in cell content of an Excel
2007 file using OLEDB in VB.NET 2005 . Here we are using OleDbConnection ,
OleDbDataAdapter , DataSet for doing these operations in an Excel file. You have to import
System.Data in the project for doing these operations . For add new content in the cell or insert a
new content , We can use the INSERT command like in SQL Operations.
sample UPDATE sql
sql = "Insert into [Sheet1$] (id,name) values('5','e')"
The follwoing picture shows before and after update of the Sheet.

Source code
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim myCommand As New System.Data.OleDb.OleDbCommand
Dim sql As String
MyConnection = New System.Data.OleDb.OleDbConnection _
("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + _
"'c:\testfile.xls';Extended Properties=Excel 8.0;")
MyConnection.Open()
myCommand.Connection = MyConnection
sql = "Insert into [Sheet1$] (id,name) values('5','e')"
myCommand.CommandText = sql
myCommand.ExecuteNonQuery()
MyConnection.Close()
Catch ex As Exception

MsgBox(ex.ToString)
End Try
MsgBox("Row Added ")
End Sub
End Class

When you execute this source code the will insert a row in the Excel file.
How to update cell data in an Excel file using OLEDB
Without using Excel Object we can insert , edit , delete , select etc. in cell content of an Excel
2007 file using OLEDB in VB.NET 2005 . Here we are using OleDbConnection ,
OleDbDataAdapter , DataSet for doing these operations in an Excel file. You have to import
System.Data in the project for doing these operations . For update the content in the cell or
modify the content in a cell , We can use the UPDATE command like in SQL Operations.
sample UPDATE sql
sql = "Update [Sheet1$] set name = 'New Name' where id=1"
The follwoing picture shows before and after update of the Sheet.

Source code
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim myCommand As New System.Data.OleDb.OleDbCommand

Dim sql As String


MyConnection = New System.Data.OleDb.OleDbConnection _
("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + _
"'c:\testfile.xls';Extended Properties=Excel 8.0;")
MyConnection.Open()
myCommand.Connection = MyConnection
sql = "Update [Sheet1$] set name = 'New Name' where id=1"
myCommand.CommandText = sql
myCommand.ExecuteNonQuery()
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
MsgBox("Updated ")
End Sub
End Class

When you execute this source code the will update the corrosponding content.
How to export from database to excel
Here we are going to export data from database to Excel file . We load the data from database to
dataset and then create a new Excel file and write the data to Excel file .
First step is to Load the Product table data to data set , for detail of Product table please refer to
Database Structure .
Next is to create a new Excel file and write the data from dataset to Excel file.
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
ds.Tables(0).Rows(i).Item(j)
Next
Next

Source code
Imports System.Data
Imports System.Data.SqlClient
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String

Dim i, j As Integer
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
connectionString = "data source=servername;" & _
"initial catalog=databasename;user id=username;password=password;"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM Product"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
ds.Tables(0).Rows(i).Item(j)
Next
Next
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
cnn.Close()
MsgBox("You can find the file C:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

How to export from DataGridView to excel

For exporting data from Datagridview to Excel , connect database and load data from database to
Datagridview and create a new excel file and write the data from Datagridview to Excel file .

First step is to Load the Product table data to DataGridView , for detail of Product table please
refer to Database Structure , and create new Excel file and write the data from Datagridview to
Excel file.
Source code
Imports System.Data
Imports System.Data.SqlClient
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String
connectionString = "data source=servername;" & _
"initial catalog=databasename;user id=username;password=password;"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT * FROM Product"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet
dscmd.Fill(ds)
DataGridView1.DataSource = ds.Tables(0)
cnn.Close()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, _


ByVal e As System.EventArgs) Handles Button2.Click
Dim
Dim
Dim
Dim
Dim
Dim

xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value
i As Integer
j As Integer

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
xlWorkSheet.SaveAs("C:\vbexcel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file C:\vbexcel.xlsx")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class

Sample Database and tables for Crystal Reports tutorials


In the following section you can see , how to create a sample Database and Tables and data for
running Crystal Reports Tutorials . All examples in the VB.NET Crystal Reports Tutorials
are based on the following database . First we have to create a database . Give the database name
as "crystaldb"

Create a DataBase "crystaldb"


In the crystaldb database , create three tables
OrderMaster , OrderDetails , Product .
OrderMaster
OrderMaster_id
OrderMaster_date
OrderMaster_customer
OrderMaster_createduser
OrderDetails
OrderDetails_id
OrderDetails_masterid
OrderDetails_productid
OrderDetails_qty
Product
Product_id
Product_name
Product_price
The following picture shows the relations of each table :

SQL command for creation tables are follows :


CREATE TABLE [dbo].[OrderMaster] (
[OrderMaster_id] [int] NOT NULL ,
[OrderMaster_date] [datetime] NULL ,
[OrderMaster_customername] [varchar] (50),
[OrderMaster_createduser] [varchar] (50)
) ON [PRIMARY]
CREATE TABLE [dbo].[OrderDetails] (
[OrderDetails_id] [int] NOT NULL ,
[OrderDetails_masterid] [int] NULL ,
[OrderDetails_productid] [int] NULL ,
[OrderDetails_qty] [int] NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[Product] (
[Product_id] [int] NOT NULL ,

[Product_name] [varchar] (50) ,


[Product_price] [numeric](18, 0) NULL
) ON [PRIMARY]
Enter data to the tables :
Order Master Table Data

Order Details Table Data

Product Table Data

VB.NET Crystal Reports from multiple tables


All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
Here we are going to do is to generate Crystal Reports from multiple tables. Here we have three
table (ordermaster , orderdetails amd product ) and we are generating report from these three
tables by connecting each tables with their related fields.
Open Visual Studio .NET and select a new Visual Basic .NET Project.

From main menu in Visual Studio select PROJECT-->Add New Item . Then Add New Item
dialogue will appear and select Crystal Reports from the dialogue box.

Select Report type from Crystal Reports gallery.

Accept the default settings and click OK.


Next step is to select the appropriate connection to your database. Here we are going to select
OLEDB connection for SQL Server
Select OLE DB (ADO) from Create New Connection .

Select Microsoft OLE DB Provider for SQL Server .

Next screen is the SQL Server authentication screen . Select your Sql Server name , enter userid
, password and select your Database Name . Click next , Then the screen shows OLE DB
Property values , leave it as it is , and click finish.
Then you will get your Server name under OLEDB Connection from there select database name
(Crystaldb) and click the tables , then you can see all your tables from your database.
Select all table from the table list to right side list box, because we are creating report from three
tables ( OrderMaster, OrderDetails, Product) .

The next step is to make relation between these selected tables. Here we are connecting the
related fields from each table. For that we arrange the tables in visible area in the list (this is not
necessary ) and select the field we are going to make relation and drag to the related field of the
other table. After made the relation the screen is look like the following picture .

Next step is to select the fields from the tables . Here we are selecting only Customername ,
orderdate from ordermastertable , Productname from product table and quantity from order
details.

Click the Finish button because now we are not using other functionalities of this wizard. After
that you will get the Crystal Reports designer window . You can arrange the fields in the designer
window according to your requirement to view the report . For rearranging you can drag the field
object in the screen . For editing right click the field object and select Edit Text Object. The
following picture shows the sample of designer window after rearrange the field.

Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET
through Crystal Reports Viewer control .
Select the default form (Form1.vb) you created in VB.NET and drag a button and
CrystalReportViewer control to your form.

Select Form's source code view and put the code on top
Imports CrystalDecisions.CrystalReports.Engine
Put the following source code in the button click event
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class

NOTES:
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give
the full path name of report here.
After you run the source code you will get the report like this.

Here we connected three tables related field and get the result . If you have any comments please
contact the email address in our contact page.

VB.NET Crystal Reports Integer parameter


All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
In this tutorial we are passing an Integer Parameter to Crystal Reports from VB.NET.

In the previous tutorial , we saw passing a string parameter to Crystal Reports from VB.NET and
get the result. This is very similar to that tutorial , so here showing only the change information
part only. So please take a look at the complete part of passing a string parameter to Crystal
Reports from VB.NET.
When we pass an Integer parameter , we have to create a new Integer parameter in the Parameter
Fields of Field Explorer. Then we will get the following screen and fill the fields like in the
picture .

After creating the parameter field , we have to create the selection formula for the Crystal
Reports . For creating selection formula , Right click on Crystal Reports designer window , select
REPORT -> SELECTION FORMULA -> RECORD .
Then you can see the record Selection Formula Editor. This for entering the selection formula.
For that you have to select the fields from above lists and make the formula .
Here we made the formula like select the records from Product table whose value is greater than
the input value. For that first we select the table field that is Product_price from Product table
and then we select the comparison operator and finally we select our Parameter we created
earlier. Double click each field then it will automatically selected

After the creation of selection formula close that screen .


Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET
through Crystal Reports Viewer control .
Select the default form (Form1.vb) you created in VB.NET and drag a Textbox , button and
CrystalReportViewer control to your form.
Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Put the following source code in the button click event
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
Dim crParameterFieldDefinitions As ParameterFieldDefinitions

Dim crParameterFieldDefinition As ParameterFieldDefinition


Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
crParameterDiscreteValue.Value = Convert.ToInt32(TextBox1.Text)
crParameterFieldDefinitions = _
cryRpt.DataDefinition.ParameterFields
crParameterFieldDefinition = _
crParameterFieldDefinitions.Item("Price")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class

NOTES:
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So 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 Product list
whose price is greater than or equal to the entered price.

Here we got the result of Product list whose price is grater than 50.

VB.NET Crystal Reports Date parameter


All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
In this tutorial we are passing a date variable to Crystal Reports from VB.NET.
In the previous tutorials , we saw passing a string parameter to Crystal Reports , integer
parameter to Crystal report from VB.NET and get the result. This tutorial is very similar to the
above two tutorials , so please take look into the two tutorials before we start this one.
When we pass a Date parameter, we have to create a new date parameter in the Parameter Fields
of Field Explorer. Then we will get the following screen and fill the fields like in the picture .

After creating the parameter field , we have to create the selection formula for the Crystal
Reports . For creating selection formula , Right click on Crystal Reports designer window , select
REPORT -> SELECTION FORMULA -> RECORD .
Then you can see the record Selection Formula Editor. This for entering the selection formula.
For that you have to select the fields from above lists and make the formula .
Here we are making the formula like , select all records details from the tables whose order date
is greater than the input date parameter. For doing this you have to select Ordermaster.orderdate ,
comparison operator and parameter date field from selection list of Formula Editor and make the
formula.

After the creation of selection formula close that screen .


Now the designing part is over and the next step is to call the created Crystal Reports in VB.NET
through Crystal Report Viewer control .
Select the default form (Form1.vb) you created in VB.NET and drag a Textbox , button and
CrystalReportViewer control to your form.
Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Put the following source code in the button click event
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
Dim crParameterFieldDefinitions As ParameterFieldDefinitions

Dim crParameterFieldDefinition As ParameterFieldDefinition


Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
crParameterDiscreteValue.Value = TextBox1.Text
crParameterFieldDefinitions = _
cryRpt.DataDefinition.ParameterFields
crParameterFieldDefinition = _
crParameterFieldDefinitions.Item("Orderdate")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class

NOTES:
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So 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 equal to the entered date.

Here we got the result of orders whose date is greater than the entered date

VB.NET Crystal Reports Load Dynamically


All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
In this section we are passing User ID , Password , Server Name and Database Name
dynamically to Crystal Reports from vb.net .
SITUATIONS :
In many situations this is useful , for example if you develop a database project in a test server
and later you have to migrate it , in such situations you have to give these information
dynamically to Crystal Reports.
In this program we are using our earlier program and pass the values dynamically to Crystal
Reports. Before we start this section take a look at the step by step Crystal Report in VB.NET .
In the step by step Crystal Report we created a report selecting all data from the Product table .
There is no chance to change the server on runtime in that case because it is a static report . Here
we are passing Server Name , UserID and Password dynamically to the Crystal Reports.
Here we use Crystal Reports ConnectionInfo .
Dim crConnectionInfo As New ConnectionInfo , and pass these arguments to ConnectionInfo
Select the default form (Form1.vb) you created in VB.NET and drag a button and
CrystalReportViewer control to your form.
Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Put the following source code in the button click event
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine

Imports CrystalDecisions.Shared
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument
Dim crtableLogoninfos As New TableLogOnInfos
Dim crtableLogoninfo As New TableLogOnInfo
Dim crConnectionInfo As New ConnectionInfo
Dim CrTables As Tables
Dim CrTable As Table
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
With crConnectionInfo
.ServerName = "YOUR SERVER NAME"
.DatabaseName = "YOUR DATABASE NAME"
.UserID = "YOUR DATABASE USERNAME"
.Password = "YOUR DATABASE PASSWORD"
End With
CrTables = cryRpt.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class

NOTES:
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give
the full path name of report here.
You have to replace the source code values of "YOUR SERVER NAME" , "YOUR
DATABASE NAME" , "YOUR DATABASE USERNAME" , "YOUR DATABASE
PASSWORD" with your correct values .
When you run this program you will get the following screen.

VB.NET Crystal Reports Formula Fields


All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
In this tutorial we are adding a Formula Field in existing Crystal Reports .
SITUATIONS :
If you have a Crystal Reports with Qty and Price , you need an additional field in your Crystal
Reports for the Total of QTY X PRICE . In this situation you have to use the Formula Field in
Crystal Reports.
In this tutorial we are showing the all orders with qty and price and the total of each row , that
means each in each row we are showing the total of qty and price. Before starting this tutorial.
Create a new Crystal Reports with fields CustomerName , Order Date , Product Name and
Product Price . If you do not know how to create this report , just look the previous tutorial
Crystal Report from multiple tables . In that report selecting only four fields , here we need one
more field Prodcut->Price .
After you create the Crystal Reports you screen is look like the following picture :

Next is to create the a Formula Field for showing the total of Qty and Price .
Right Click Formula Field in the Field Explorer and click New. Then you will get an Input
Message Box , type Total in textbox and click Use Editor

Now you can see Formula Editor screen . Now you can enter which formula you want . Here we
want the result of Qty X Price . For that we select OrderDetails.Qty , the multiplication operator
and Product.Price . Double click each field for selection.

Now you can see Total Under the Formula Field . Drag the field in to the Crystal Reports where
ever you want .

Now the designing part is over . Select the default form (Form1.vb) you created in VB.NET and
drag a button and CrystalReportViewer control to your form.
Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine
Put the following source code in the button click event
Download Source Code

Print Source Code


Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class

NOTES:
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So 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


All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .

In this tutorial we are taking the sum of field value of Total . This is the continuation of the
previous tutorial Crystal Report Formula Field . So before we start this tutorial , take a look at
the previous tutorial Crystal Report Formula Field.
Here we are taking the grand total of the Total field . The Total field is a Formula field is the
result of qty X price .
In the Crystal Reports designer view right click on the Report Footer , just below the Total field
and select Insert -> Summary .

Then you will get a screen , select the Total from the combo box and Sum from next Combo Box
, and summary location Grand Total (Report Footer) . Click Ok button

Now you can see @Total is just below the Total field in the report Footer.

Now the designing part is over . Select the default form (Form1.vb) you created in VB.NET and
drag a button and CrystalReportViewer control to your form.
Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine
Put the following source code in the button click event
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
End Class

NOTES:
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So 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 PDF


Exporting from Crystal Reports to PDF format , we are using Crystal Reportss
CrExportOptions . Also we have to set PdfRtfWordFormatOptions and
ExportFormatType.PortableDocFormat . In the following example you can see how to export a
Crystal Reports as a PDF format file.
All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
In this tutorial we are using our earlier program step by step Crystal Report for pull data from
database to Crystal Reports . Before we start this section take a look at the step by step Crystal
Report in VB.NET .
In the step by step Crystal Report we pull all data from Product table , here now we are exporting
that data to a PDF format file.
Select the default form (Form1.vb) you created in VB.NET and drag two buttons (Button1,
Button2 ) and CrystalReportViewer control to your form.
Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine
Put the following source code in the button click events
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Dim cryRpt As New ReportDocument
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions()

CrDiskFileDestinationOptions.DiskFileName = _
"c:\crystalExport.pdf"
CrExportOptions = cryRpt.ExportOptions
With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.PortableDocFormat
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
cryRpt.Export()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

NOTES:
cryRpt.Load("PUT

CRYSTAL

REPORT

PATH

HERE\CrystalReport1.rpt")

The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give
the
full
path
name
of
report
here.
When you run this program you will get the PDF file (crystalExport.pdf) in your computer's C:

VB.NET Crystal Reports Export to Excel


Exporting from Crystal Reports to Excel format , we are using Crystal Reports
CrExportOptions . Also we have to set ExcelFormatOptions and ExportFormatType.Excel . In
the following example you can see how to export a Crystal Reports as a Excel format file.
All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
In this tutorial we are using our earlier program step by step Crystal Report pull data from
database to Crystal Reports . Before we start this section take a look at the step by step Crystal
Report in VB.NET .
In the step by step Crystal Report we pull all data from Product table , here now we are exporting
that data to a Excel format file.
Select the default form (Form1.vb) you created in VB.NET and drag two buttons (Button1,
Button2 ) and CrystalReportViewer control to your form.
Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine
Put the following source code in the button click events

Download Source Code


Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Dim cryRpt As New ReportDocument
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New ExcelFormatOptions
CrDiskFileDestinationOptions.DiskFileName = _
"c:\crystalExport.xls"
CrExportOptions = cryRpt.ExportOptions
With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.Excel
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
cryRpt.Export()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

NOTES:
cryRpt.Load("PUT

CRYSTAL

REPORT

PATH

HERE\CrystalReport1.rpt")

The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give
the
full
path
name
of
report
here.
When you run this program you will get the Excel file (crystalExport.xls) in your computer's C:

Email a Crystal Reports from VB.NET


For Email a Crystal Reports , we have to export the Crystal Reports in any of the File Format
available in Crystal Reports and then Email it.

All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
In this tutorial we use the tutorial Export Crystal Report to PDF file . So before we start this
section please take a look at the tutorial Export Crystal Report to PDF file
After export the Crystal Reports as a PDF file , the next step is to email that file . For that here
we are using System.Web.Mail . We have to provide the necessary information to configuring
SmtpMail client and send the exported file as attachment .
Select the default form (Form1.vb) you created in VB.NET and drag two buttons (Button1,
Button2 ) and CrystalReportViewer control to your form.
Select Form's source code view and import the following :
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Web.Mail
Put the following source code in the button click events
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Web.Mail
Public Class Form1
Dim cryRpt As New ReportDocument
Dim pdfFile As String = "c:\ProductReport1.pdf"
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions
CrDiskFileDestinationOptions.DiskFileName = pdfFile
CrExportOptions = cryRpt.ExportOptions

With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.PortableDocFormat
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
cryRpt.Export()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
sendMail()
End Sub
Private Sub sendMail()
Try
Dim Smtp As SmtpMail
SmtpMail.SmtpServer.Insert(0, "your hostname")
Dim Msg As MailMessage = New MailMessage
Msg.To = "to address here"
Msg.From = "from address here"
Msg.Subject = "Crystal Report Attachment "
Msg.Body = "Crystal Report Attachment "
Msg.Attachments.Add(New MailAttachment(pdfFile))
Smtp.Send(Msg)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

NOTES:
cryRpt.Load("PUT

CRYSTAL

REPORT

PATH

HERE\CrystalReport1.rpt")

The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give
the
full
path
name
of
report
here.
Before you run this programme , you have to provide the necessary SMTP informations , that is
your HOSTNAME , FROM ADDRESS and TO ADDRESS to the SMTP client.

Crystal Reports Without Database


Usually Crystal Reports we are using to fetch data from database and show it as a report. Here
we are going to generate a Crystal Reports without using a datbase . For generating a Crystal
Reports without database , here we are using a Strongly Typed Dataset and a Data Table.
The basics of Crystal Reports creation you can find in the previous section of this tutorial ,
before we start this tutorial you can take a look at the step by step Crystal Report.
Generating a Strongly Typed DataSet

Create a new VB.NET Project and accept the default settings. Create a new Dataset from Project
- Add New Item Dialogue Box.

Accept the default name DataSet1.xsd .


Create a data table for DataSet1.xsd .
Select DataSet1.xsd from Solution Explorer and right click . Select datatable from the menu.
Then you will get a datatable in the Datast . Right click the datatable and select Add-Column .

Here we are making a two column Crystal Reports , so we need two column in the data table .
Add and ID column and Name column in the Data Table.

Now the dataset part is over . Next step is to create a Crystal Reports from this Dataset . Before
going to make Crystal Reports design please take a look at step by step Crystal Report for easy
creation of Crystal Reports.
Select a new Crystal Reports from Add New Item menu and accept the default settings. The next
screen is to select appropriate data source . There you can find the Datatable1 from Project data ADO.NET Datasets , and select Datatable1 to the right side.

Click Next button and select ID and Name from the datatable1 to right side and click finish.

Now the Crystal Reports designer part is over . Next part is to create data for the Crystal
Reports . For that we have to create a Data Table through programmatically and add data to
dataset1.
Select the default form (Form1.vb) you created in VB.NET and drag one button and
CrystalReportViewer control to your form.
Put the following source code in the button click events
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim ds As New DataSet1
Dim t As DataTable = ds.Tables.Add("Items")
t.Columns.Add("id", Type.GetType("System.Int32"))
t.Columns.Add("Item", Type.GetType("System.String"))

Dim r As DataRow
Dim i As Integer
For i = 0 To 9
r = t.NewRow()
r("id") = i
r("Item") = "Item" & i
t.Rows.Add(r)
Next
Dim objRpt As New CrystalReport1
objRpt.SetDataSource(ds.Tables(1))
CrystalReportViewer1.ReportSource = objRpt
CrystalReportViewer1.Refresh()
End Sub
End Class

Crystal Reports from SQL Query String


We can create Crystal Reports in VB.NET using SQL Query String . Here we create a Strongly
Typed dataset for Crystal Reports design and create a connection object and execute the SQL
Query String .
All Crystal Report programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
The basics of Crystal Reports creation you can find in the previous section of this tutorial ,
before we start this tutorial you can take a look at the step by step Crystal Report.
Generating a Strongly Typed DataSet
In the previous section you can see a detailed tutorial about to create a strongly typed datset and
its Crystal Reports design . After create the dataset and Crystal Reports design you should create
a connection object and fetch the data from database.
Select the default form (Form1.vb) you created in VB.NET and drag one button and
CrystalReportViewer control to your form.
Put the following source code in the button click events
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click


Dim ds As New DataSet1
Dim cnn As SqlConnection
Dim connectionString As String
Dim sql As String
connectionString = "data source=servername; _
initial catalog=crystaldb;user id=username;password=password;"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = "SELECT Product_id,Product_name,Product_price FROM Product"
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet1
dscmd.Fill(ds, "Product")
MsgBox(ds.Tables(1).Rows.Count)
cnn.Close()
Dim objRpt As New CrystalReport1
objRpt.SetDataSource(ds.Tables(1))
CrystalReportViewer1.ReportSource = objRpt
CrystalReportViewer1.Refresh()
End Sub
End Class

NOTE
:
You have to provide the necessary databse information to Connection String.

Crystal Reports from SQL Query String


In usual practice , Crystal Reports we are getting from pre defined columns. But we can make
Crystal Reports from Dynamic column . Here we are going to do the dynamic Crystal Reports
from SQL statements . That is we enter SQL in textbox and get the Crystal Reports according to
the SQL statement.

All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .
Create a new VB.NET project and add a Strongly Typed Dataset . Before creating a Strongly
Typed take a look at the detailed tutorial of create a strongly typed datset and add five column in
the Datatable. Here we are limiting as five column , but you can add any number of column
according to your requirements.

Next step is to create a Crystal Reports design from the Strongly Typed dataset.

Select all the column from dataset.

Select the default form(Form1.vb) and add a TextBox , Button and Crystal Reports Viewer .
Here we are going to pass the SQl statements to Crystal Reports at runtime . For that we parsing
the SQL statement before we passing it to Crystal Reports. So we create a function for parsing
SQL statements.
Public Function procesSQL() As String
Put the following vb.net source code in your form and run the program .
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Data
Public Class Form1
Dim objRpt As New CrystalReport1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim cnn As SqlConnection
Dim connectionString As String

Dim sql As String


connectionString = "data source=SERVERNAME; _
initial catalog=crystaldb;user id=sa;password=PASSWORD;"
cnn = New SqlConnection(connectionString)
cnn.Open()
sql = procesSQL()
Dim dscmd As New SqlDataAdapter(sql, cnn)
Dim ds As New DataSet1
dscmd.Fill(ds, "Product")
objRpt.SetDataSource(ds.Tables(1))
CrystalReportViewer1.ReportSource = objRpt
CrystalReportViewer1.Refresh()
End Sub
Public Function procesSQL() As String
Dim sql As String
Dim inSql As String
Dim firstPart As String
Dim lastPart As String
Dim selectStart As Integer
Dim fromStart As Integer
Dim fields As String()
Dim i As Integer
Dim MyText As TextObject
inSql = TextBox1.Text
inSql = inSql.ToUpper
selectStart = inSql.IndexOf("SELECT")
fromStart = inSql.IndexOf("FROM")
selectStart = selectStart + 6
firstPart = inSql.Substring(selectStart, (fromStart - selectStart))
lastPart = inSql.Substring(fromStart, inSql.Length - fromStart)

fields = firstPart.Split(",")
firstPart = ""
For i = 0 To fields.Length - 1
If i > 0 Then
firstPart = firstPart & " , " _
& fields(i).ToString() & " AS COLUMN" & i + 1
MyText = CType(objRpt.ReportDefinition.ReportObjects("Text" _
& i + 1), TextObject)
MyText.Text = fields(i).ToString()
Else
firstPart = firstPart & fields(i).ToString() & _
" AS COLUMN" & i + 1
MyText = CType(objRpt.ReportDefinition.ReportObjects("Text" &
i + 1), TextObject)
MyText.Text = fields(i).ToString()
End If

Next
sql = "SELECT " & firstPart & " " & lastPart
Return sql
End Function
End Class

NOTE
:
You have to provide the necessary databse information to Connection String.

Crystal Reports from XML File


In this section you can see , creating a Crystal Reports from XML file instead of database . This
is very similer to creating Crystal Reports from database , the only difference is to sslect the data
source as your XML file.
Here we are creating an XML file name is Product is XML file the same structure of the Product
table in the sample Database Structure.
Download Product.XML

The basics of Crystal Reports creation provided in previous tutorials , if you dont have much
knowledge in Crystal Reports , take a look at the tutorial step by step Crystal Report before start
this section.

The change happen only from previous report , when you select Data for Crsyatl Report , you
have to select Create New Connection - Database Files and select the XML file you want to
generate Crystal Reports (In this case you select the Product.xml ).

Select all the fields from Product and click finish button
Now the designer part is over . Next step is to select the default form(Form1.vb) and add a
Button and Crystal Reports Viewer to the Form.
Put the following vb.net source code in your form and run the program .
Download Source Code
Print Source Code
Imports CrystalDecisions.CrystalReports.Engine
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cryRpt As New ReportDocument
cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub

End Class

cryRpt.Load("PUT
CRYSTAL
REPORT
PATH
HERE\CrystalReport1.rpt")
The Crystal Report is in your project location, there you can see CrystalReport1.rpt . So give
the full path name of report here.

Create a Subreport in Crystal Reports


Subreport in Crystal Reports means a Report within a Report . When we want to show some
additional information about the data in the Crystal Reports , we use the subreports to show the
details. Subreports we show within the main Crystal Reports and also we can show it as OnDemand report , that means we put an Hyper link in the row, and when user click that hyper link
then will get the subreport.
This section we are showing the subreport within the Crystal Reports . That is for each row there
is a subreoprt for the details.

All Crystal Reports programming samples in this tutorials is based on the following database
(crystaldb) . Please take a look at the database structure before you start this tutorial - Click here
to see Database Structure .

Here we are create an order report based on three tables in the database and show a subreoprt for
each row of the specified Product Name. Here we are using our earlier program Crystal Report
from multiple tables to show the main Crystal Reports Data , so please refer Crystal Report from
multiple tables before start this section .
Create a Crystal Reports using three tables and select customername , date , product and qty . It
will explain in detail the previous section Crystal Report from multiple tables .
Next step is to create a subreport inside the main report. Here we are showing the Product details
in each row of the specified product in the main row.
After create the main report , right click on Crystal Reports designer window and select InsertSubreport.

Then you will get the subreport object , drag the object in the designer window at the down part
of the details tab , just below the fields in the details tab. When you release the mouse you will
get a dialogue box asking report name . Enter the report name you want and click the Report
Wizard button.
The wizard shows the table selection screen and select the table . Here in this case we are
selecting the Product Table from the list and click next .
Next screen is showing the table , from there select the fields you want to show the data and click
finish. The you will get the subreport main screen again and select Link tab .
The link tab is making relation with your main Report and subreport . Here we are linking the
productname from main report to the subreport. For that select Product.Product_name from
Available fields.

Accept the other settings as it is in the screen and click ok. Now you can see the subreport object
in the screen , if you want to modify subreport design , double click on subreport object and you
can design subreport.

Now the designer part is over . Next step is to select the default form(Form1.vb) and add a
Button and Crystal Reports Viewer to the Form.
Put the following vb.net source code in your form and run the program .
Download Source Code
Print Source Code

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim crp As New CrystalReport1
CrystalReportViewer1.ReportSource = crp
CrystalReportViewer1.Refresh()
End Sub
End Class

Create a Subreport in Crystal Reports with Link


In the previous section Subreport in Crystal Report is described how to insert a subreport in
Crystal Reports . In that case the subreport is embedded within the main Crystal Reports. Here
we are creating a subreport , and the subreport has only a link in the main Report , on-demand
subreports . That is when the user click the link , then only the subreport display.

Here we are using our previous example Subreport in Crystal Report and make a link in the min
Crystal Reports for on-demand subreport.

Select the subreport object in the Crystal Reports and right click , then select Format Object .

Then you will get Format Editor . Select Subreport tab from Format Editor , you can find there a
check box On-demand Subreport . You have to select that check box , then the subreport become
as a link in your main Crystal Reports. If you want to change the title , you can change it in
subreport name textbox. Finally click OK button.

Now the designing part is over and you are ready to generate subreport on-demand. Next step is
to select the default form(Form1.vb) and add a Button and Crystal Report Viewer to the Form.
Put the following vb.net source code in your form and run the program .
Download Source Code
Print Source Code

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim crp As New CrystalReport1
CrystalReportViewer1.ReportSource = crp
CrystalReportViewer1.Refresh()
End Sub
End Class

How to deploy Crystal Reports on Clinet Machine


Crystal Reports for Visual Studio ships with your deployment projects that enable you to
deploy Crystal Reports components and assemblies on the target machine. We can use different
approaches to install Crystal Reports runtime files on the target machine .
If you are using Visual Studio then during your setup and deployment you can add the
CRRedist2005_x86.msi file to your setup file and distribute it as a single setup file . The installer
can execute the setup file automatically with your .Net Project in a single click. You can find the
CRRedist2005_x86.msi file in your system's C:\Program Files\Microsoft Visual Studio
8\SDK\v2.0\BootStrapper\Packages\CrystalReports . Also you can distribute the
CRRedist2005_x86.msi separately and install it on the target machine.
The other way to install Crystal Reports on target machine is to create a setup file using Merge
Modules and distribute it with your application or as a separate setup file. Click the following
link to see how to make a setup file with Merge Modules.
Crystal Reports installer using Merge Modules.

How to create Crystal Reports installer using


Merge Modules
Crystal Reports uses merge modules to ensure the correct report components and assemblies are
installed with your deployment project. A 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 Crystal Reports Client side installation using Merge Modules.
Before creating a setup project, make sure that the following files exist in the \Program
Files\Common Files\Merge Modules folder.
CrystalReportsRedist2005_x86.msm
Microsoft_VC80_ATL_x86.msm
policy_8_0_Microsoft_VC80_ATL_x86.msm

Steps to create Setup file.


1) Make sure the above mentioned files are in the \Program Files\Common Files\Merge
Modules folder , If the files are not there you can download the file and copy it to the folder
\Program Files\Common Files\Merge Modules .
Download: https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/11688
2) Open your Visual Studio
3) Select "New Project" from File menu.

4) Select "Setup and Deployment" from "Other Project Types"


5) In the "Solution Explorer", select your setup project, right-click, and select Add and Merge
Module from the menu.

6) Select CrystalReportsRedist2005_x86.msm to your setup project.


The file available at \Program Files\Common Files\Merge Modules

Then you can see Microsoft_VC80_ATL_x86.msm and


policy_8_0_Microsoft_VC80_ATL_x86.msm will be automatically added in the Detected
Depencies section.
7) Build your project.
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.

How to send email from VB.NET


VB.NET using SMTP protocol for sending email . SMTP stands for Simple Mail Transfer
Protocol . VB.NET using System.Net.Mail namespace for send mail . We can instantiate
SmtpClient class and assign the Host and Port . The default port using SMTP is 25 , but it may
vary different Mail Servers .In the following example shows how to send an email from a Gmail
address.
The Gmail SMTP server name is smtp.gmail.com and the port using send mail is 587 . Here
using NetworkCredential for password based authentication.
Download Source Code
Print Source Code
Imports System.Net.Mail
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Credentials = New _
Net.NetworkCredential("username@gmail.com", "password")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
mail = New MailMessage()
mail.From = New MailAddress("YOURusername@gmail.com")
mail.To.Add("TOADDRESS")
mail.Subject = "Test Mail"
mail.Body = "This is for testing SMTP mail from GMAIL"
SmtpServer.Send(mail)
MsgBox("mail send")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

You have to provide the informations like your gmail username and password , and the to
address also.

VB.NET Send email using CDOSYS


Using CDOSYS is another easy way to send email from VB.NET . For sending email using
CDOSYS , you have to send email from Windows 2000/XP and also you have to be enabled
SMTP Service in IIS .
Requirements

Windows XP/ Windows2000


Internet Information Services (IIS)
SMTP Services in IIS should be enable.

Download Source Code


Print Source Code
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim CDOSYS As Object
Const cdoSendUsingPickup = 1
Const strPickup = "c:\inetpub\mailroot\pickup"
CDOSYS = CreateObject("CDO.Message")
CDOSYS.Configuration.Fields.item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") _
= cdoSendUsingPickup
CDOSYS.Configuration.Fields.item _
("http://schemas.microsoft.com/cdo/configuration" & _
/smtpserverpickupdirectory") _
= strPickup
CDOSYS.Configuration.Fields.Update()
CDOSYS.To = "TO ADDRESS"
CDOSYS.From = "FROM ADDRESS"
CDOSYS.Subject = "CDO Test"
CDOSYS.TextBody = "Send Email from vb.net using CDOSYS"
CDOSYS.Send()
CDOSYS = Nothing
MsgBox("mail send")
End Sub
End Class

You have to provide the informations like To Address , From Address and it is very important to
enable your SMTP services in IIS .

How to find IP Address of Host


Syste.net namespace provide the infomation about IP Address .

If you pass localhost in GetHostByName return the IP Address of local machine .


Download Source Code
Print Source Code
Imports System.Net
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim hostname As IPHostEntry = Dns.GetHostByName(TextBox1.Text)
Dim ip As IPAddress() = hostname.AddressList
TextBox2.Text = ip(0).ToString()
End Sub
End Class

How to read a URL Content


When we want to read content of an HTML page from a remote webserver , in vb.net we are
using WebRequest , WebResponse . WebResponse return a StreamReader and we can retrieve
the content using a StreamReader.

Download Source Code


Print Source Code
Imports System.Net
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim inStream As StreamReader
Dim webRequest As WebRequest
Dim webresponse As WebResponse
webRequest = webRequest.Create(TextBox1.Text)
webresponse = webRequest.GetResponse()
inStream = New StreamReader(webresponse.GetResponseStream())
TextBox2.Text = inStream.ReadToEnd()
End Sub
End Class

VB.NET Socket Programming


A Socket is an End-Point of To and From (Bidirectional) communication link between two
programs (Server Program and Client Program ) running on the network . We need two programs
for running a socket program. A Server Socket Program ( Server ) and a Client Socket Program
( Client ) .
Server Program: A Server Socket Program running on a computer has a socket that bound to a
Port Number on that computer and listening to the client's requests.
Client Program: Client Socket Program have to know the IP Address ( Hostname ) of the
computer that the Server Socket Program resides and the Port Number assign for listening for
client's request .

Once the communication is established , the Server and Client can read or write their own
sockets.
There are two types of communication protocol use for Socket Programming TCP/IP
( Transmission Control Protocol/Internet protocol ) Communication and UDP/IP ( User
Datagram Protocol/Internet protocol ) Communication .

In the following section we are going to communicate a Server Socket Program and Client
Socket Program through VB.NET using TCP/IP Communication.

In the above picture shows the communication interfaces .


Server Socket Program:
Here Server Socket Program is done through a Console based VB.NET application . Here the
Server listening for the client's request , and when the server get a request from the Client ,
Server sends the response to Client . Click the following link to see in detail of a Server Socket
Program .
Client Socket Program:
The Client Socket Program is a windows based application . When the client start its get connect
the server and send requests , and also receive the response from Server . Click the following
link to see in detail of Client Socket Program.
How to run this program ?

The Socket Programming has two sections.


1. Server Socket Program
2. Client Socket Program
When you finish coding the program , First you have to start Server Socket Program , then you
will get the DOS screen with a message Server Started .
Next step is to start Client Socket Program . Then you will get message in client screen Client
Started , at the same time you check with server screen a message Accept connection from
client .
Now your Server Socket Program and Client Socket Program get connected . If you want to test
the communication , you click the button ( Click here to send data to Server ) in client window ,
then you can see changes in Server and Client screen messages .

VB.NET Client Socket Program

The Socket Programming has two sections.


1. Server Socket Program
2. Client Socket Program
The Client Socket Program is the continuation of the Server Socket Program . The Client
Socket Program is a Windows based application . Client connect to the Port 8888 of the Server
Socket Program , and the IP Address (Computer Name) here we give as 127.0.0.1 , because the
Server and client running on the same machine .

clientSocket.Connect("127.0.0.1", 8888)
When client gets connected , it reads data from NetworkStream , and also write to
NetworkStream . When you start the client program you will get message client started . When
press the button at the bottom its send a message to Server and also receive a message from
Server.
Download Source Code
Print Source Code
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim serverStream As NetworkStream = clientSocket.GetStream()
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes("Message from Client$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
Dim inStream(10024) As Byte
serverStream.Read(inStream, 0, CInt(clientSocket.ReceiveBufferSize))
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
msg("Data from Server : " + returndata)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
msg("Client Started")
clientSocket.Connect("127.0.0.1", 8888)
Label1.Text = "Client Socket Program - Server Connected ..."
End Sub
Sub msg(ByVal mesg As String)
TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + mesg
End Sub
End Class

Brfore you run the Client Socket Program you should start Server Socket Program first . For
more details of running this program , take a look at the VB.NET Socket Programming .

VB.NET MultiThreaded Socket Programming


Multithreaded Socket Programming means that a Multithreaded Server can communicate with
more than one clients at the same time . In the previous section Socket Programming , the Server
Socket Program can communicate with only one client at a time . That means it s not possible to

connect another Client Socket Program at the same time to communicate with Server . From the
following figure you can understand how to a Server can communicate with more than one client
at the same time .You can see the basics of Socket Programming in the previous section , take a
look at Socket Programming before you start this section.

The basic idea behind Multithreaded Socket Programming is, whenever Server gets a
connection request from Client , the Server create a separate ( independent ) Thread for the each
Client request. That means for each Client, there is a separate Client Thread in Server . So the
Client can communicate independently with their own Client Thread in Server.

In the following sections you can see in detail of How a Multithreaded Socket Programming
can communicate with more than one client at the same time.
The Multithreaded Socket Programming has two sections.
1. Multithreaded Server Socket Program
2. Multithreaded Client Socket Program
How to run this program ?
Create Multithreaded Server Socket Program and Multithreaded Client Socket Program and run
the Server program first . Then you will get message of "Server started" . Next you start the
Client program , then you can see the message from Server . You can start more than one client
same time and communicate with Server . For each client Server responds with the Clients
Connection ID Number.

VB.NET MultiThreaded Server Socket Programming


MultiThreaded Server Socket Program here is a VB.NET Console based application , that can
handle multiple clients at the same time. You can see the basics of Socket Programming in the
previous section , take a look at Socket Programming before you start this section.
The Multithreaded Socket Programming has two sections.
1. Multithreaded Server Socket Program
2. Multithreaded Client Socket Program

Here we create a Server Socket from TcpListener class and listen to PORT 8888 . When the
server gets a request from Client , the Server pass the instance of the client request to a separate
class handleClient . In handleClient class there is a Thread , handling the communication
between the instance of Server side client and Client from outside .
For each request , in Server there is a new thread instant is create for communication , so we can
connect more than one client at the same time to Server and communicate independently .
Create a new VB.NET Console Application project and put the following source code in the
project.
Download Source Code
Print Source Code
Imports System.Net.Sockets
Imports System.Text
Module Module1
Sub Main()
Dim serverSocket As New TcpListener(8888)
Dim clientSocket As TcpClient
Dim counter As Integer
serverSocket.Start()
msg("Server Started")
counter = 0
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
msg("Client No:" + Convert.ToString(counter) + " started!")
Dim client As New handleClinet
client.startClient(clientSocket, Convert.ToString(counter))
End While
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Public Class handleClinet
Dim clientSocket As TcpClient
Dim clNo As String
Public Sub startClient(ByVal inClientSocket As TcpClient, _
ByVal clineNo As String)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub

Private Sub doChat()


Dim requestCount As Integer
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim sendBytes As [Byte]()
Dim serverResponse As String
Dim rCount As String
requestCount = 0
While (True)
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
msg("From client-" + clNo + dataFromClient)
rCount = Convert.ToString(requestCount)
serverResponse = "Server to clinet(" + clNo + ") " + rCount
sendBytes = Encoding.ASCII.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Flush()
msg(serverResponse)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
End Class
End Module

The
1.
2.

Multithreaded
Socket
Multithreaded
Multithreaded

Programming
has
Server
Socket
Client
Socket

two

sections.
Program
Program

You have to run Server program first and then Client program , then only you can communicate
with Server and Client each other .

VB.NET MultiThreaded Client Socket Programming


The Multithreaded Socket Programming has two sections.
1. Multithreaded Server Socket Program
2. Multithreaded Client Socket Program

MultiThreaded Client Socket Program is a windows based application . Here the client
program is connected to Server's PORT 8888 , and IP Address here we give Server Address as "
127.0.0.1 " , because Server and Client program run on the same machine.
clientSocket.Connect("127.0.0.1", 8888)
When the Client get conncted to the Server , the Server make a separate thread for Client's
communication . So we can connect more than one client and communicate at the same time.
Create a new VB.NET Windows based application and put the following source code in the
Project.
Download Source Code
Print Source Code
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim serverStream As NetworkStream = clientSocket.GetStream()
Dim buffSize As Integer
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes("Message from Client$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
Dim inStream(10024) As Byte
buffSize = clientSocket.ReceiveBufferSize
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
msg("Data from Server : " + returndata)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
msg("Client Started")
clientSocket.Connect("127.0.0.1", 8888)
Label1.Text = "Client Socket Program - Server Connected ..."
End Sub
Sub msg(ByVal mesg As String)
TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + mesg
End Sub
End Class

The
1.

Multithreaded
Socket
Multithreaded

Programming
has
Server
Socket

two

sections.
Program

2.

Multithreaded

Client

Socket

Program

You have to run Server program first and then Client program , then only you can communicate
with Server and Client each other .

VB.NET Chat Server Program


Multithreaded Socket Programming is the basic idea behind a TCP Chat Server communication.
In the previous section Multithreaded Socket Programming we can see a Multithreaded Server
Socket Program communicate with more than one Client at the same time . But there the
communication is happening only between Server to Client or Client to Server , there is no
communication between Client to Client . In a Multithreaded Chat Server , a Client can
communicate with any number of Clients , currently connected on the Chat Server .

Each Clients send messages to Server and the Server broadcast the message to all Clients
currently connected to the Chat Server . From the following diagram you can see how a VB.NET
TCP Chat Server is handling communication between Client to Client .

The VB.NET Multithreaded Chat Server program has two sections.


1. Chat Server
2. Chat Client
Download Chat Server Program .
Chat Server Download
Chat Client Download
How to run Chat Server program ?
After create the Chat Server and Chat Client , run the Server program first and then run the
Client program . In the Client program Enter a Chat name and click the " Connect to Server "
button . Then you can see the message in the Server program User Joined Chat Room . Similarly
you can connect more than one Clients at the same time and start chatting each other. It is better
to Compile and Build the program and run from the .exe files .

VB.NET Chat Server


The basic function of the Chat Server here is to listening for the connection request from Clients
and when the Server get a message , it Broadcast the message to all Clients currently connected
to the Server .

The VB.NET Multithreaded Chat Server Program has two sections.


1. Chat Server
2. Chat Client
The Chat Server here is a VB.NET Console based application and is listening to the PORT 8888
for the connection request from clients . When the server gets a connection request , it add the
name of the Client into a clientsList ( Here it is a Hashtable ) and create a new thread for
communication with Server . When the Server get a message from any client , it select all the
Clients from clientsList and send the message to all Clients ( ie we can say Broadcast ) in the
clientsList . So each Client can see the message each other and they can communicate through
Chat Server.
The client list we implemented here in a HashTable . The clientsList stores the Client Name ( ie
the first message from Client ) and an instance of the Client Socket .
When a Chat Client connected to Server , the Server create a new Thread for communication .
Here we implement a Class handleClient for handling Client as a separate Thread . The Class
handleClient has a function doChat() is handling the communication between the Server side
Client Socket and the incoming Client Socket.
When Server get a message from any of the currently connected Chat Client , the Server
Broadcast the message to all Clients. Here we implement a function broadcast for sending
messages to all Clients .
Create a new VB.NET Console based application and put the following source code into the
Project.

Download Source Code


Print Source Code
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim clientsList As New Hashtable
Sub Main()
Dim serverSocket As New TcpListener(8888)
Dim clientSocket As TcpClient
Dim counter As Integer
serverSocket.Start()
msg("Chat Server Started ....")
counter = 0
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
clientsList(dataFromClient) = clientSocket
broadcast(dataFromClient + " Joined ", dataFromClient, False)
msg(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
End While
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Private Sub broadcast(ByVal msg As String, _
ByVal uName As String, ByVal flag As Boolean)
Dim Item As DictionaryEntry
For Each Item In clientsList
Dim broadcastSocket As TcpClient
broadcastSocket = CType(Item.Value, TcpClient)
Dim broadcastStream As NetworkStream = _

broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
Next
End Sub
Public Class handleClinet
Dim clientSocket As TcpClient
Dim clNo As String
Dim clientsList As Hashtable
Public Sub startClient(ByVal inClientSocket As TcpClient, _
ByVal clineNo As String, ByVal cList As Hashtable)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub doChat()
'Dim infiniteCounter As Integer
Dim requestCount As Integer
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim sendBytes As [Byte]()
Dim serverResponse As String
Dim rCount As String
requestCount = 0
While (True)
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
msg("From client - " + clNo + " : " + dataFromClient)
rCount = Convert.ToString(requestCount)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub

End Class
End Module

Download
Chat
Chat

Chat

Server
Server

Program
Download

Client

Download

Refer to Chat Server Program for how to run this program .

VB.NET Chat Client


The Chat Client is a Windows based Application and its main function is to send message to
Chat Server.

The VB.NET Multithreaded Chat Server Program has two sections.


1. Chat Server
2. Chat Client
The Chat Client here is to connect the PORT 8888 of the Chat Server in " 127.0.0.1 " . Here we
give " 127.0.0.1 " , because Chat Server and Chat Client are running on the same machine .
When we start the Chat Client program , we have to enter a User Name for identifying in Server
. The Client program connect to the Chat Server and start a Thread for receive the messages
from client, . Here we implement an infinite loop in the function getMessage() and call this
function in a Thread .
Create a new VB.NET Windows based project and put the source code in it.

Download Source Code


Print Source Code
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Dim readData As String
Dim infiniteCounter As Integer
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(TextBox2.Text + "$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
End Sub
Private Sub msg()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf msg))
Else
TextBox1.Text = TextBox1.Text + _
Environment.NewLine + " >> " + readData
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
readData = "Conected to Chat Server ..."
msg()
clientSocket.Connect("127.0.0.1", 8888)
'Label1.Text = "Client Socket Program - Server Connected ..."
serverStream = clientSocket.GetStream()
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(TextBox3.Text + "$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
Dim ctThread As Threading.Thread = _
New Threading.Thread(AddressOf getMessage)
ctThread.Start()
End Sub
Private Sub getMessage()
For infiniteCounter = 1 To 2
infiniteCounter = 1
serverStream = clientSocket.GetStream()
Dim buffSize As Integer
Dim inStream(10024) As Byte
buffSize = clientSocket.ReceiveBufferSize
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)

readData = "" + returndata


msg()
Next
End Sub
End Class

Download
Chat

Chat

Chat

Server

Server

Program
Download

Client

Download

Refer to Chat Server Program for how to run this program .

VB.NET Email Attachment


The System.Net classes uses to communicate with other applications by using the HTTP, TCP,
UDP, Socket etc. Microsoft .Net languages uses System.Net.Mail namespace for sending email .
From the previous chapters we learned how to send an email with a text body. Here we are trying
to send an eamil with attachment.
Dim attachment As System.Net.Mail.Attachment
attachment = New System.Net.Mail.Attachment("your attachment file")
mail.Attachments.Add(attachment)

The following VB.NET source code shows how to send an email with an attachment from a
Gmail address . The Gmail SMTP server name is smtp.gmail.com and the port using send mail is
587 . Here using NetworkCredential for password based authentication.
SmtpServer.Port = 587
SmtpServer.Credentials = New System.Net.NetworkCredential("username",
"password")
SmtpServer.EnableSsl = True

Download Source Code


Print Source Code
Imports System.Net.Mail
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles Button1.Click
Dim mail As New MailMessage()
Dim SmtpServer As New SmtpClient("smtp.gmail.com")
mail.From = New
MailAddress("your_email_address@gmail.com")
mail.[To].Add("to_address")

mail.Subject = "Test Mail - 1"


mail.Body = "mail with attachment"

attachment file")

Dim attachment As System.Net.Mail.Attachment


attachment = New System.Net.Mail.Attachment("your
mail.Attachments.Add(attachment)

SmtpServer.Port = 587
SmtpServer.Credentials = New
System.Net.NetworkCredential("username", "password")
SmtpServer.EnableSsl = True

End Sub
End Class

SmtpServer.Send(mail)
MessageBox.Show("mail Send")

ADO.NET Architecture
ADO.NET is a data access technology from Microsoft .Net Framework , which provides
communication between relational and non-relational systems through a common set of
components . ADO.NET consist of a set of Objects that expose data access services to the .NET
environment. ADO.NET is built for disconnected architecture , so it enables truly disconnected
Data Access and Data Manipulation through its Dataset Object, which is completely independent
from the Data Source.

The two key components of ADO.NET are Data Providers and DataSet . The .Net Framework
includes mainly three Data Providers for ADO.NET. They are the Microsoft SQL Server Data
Provider, OLEDB Data Provider and ODBC Data Provider. SQL Server uses the SqlConnection

object , OLEDB uses the OleDbConnection Object and ODBC uses OdbcConnection Object
respectively.

The four Objects from the .Net Framework provide the functionality of Data Providers in the
ADO.NET. They are Connection Object, Command Object , DataReader Object and
DataAdapter Object. The Connection Object provides physical connection to the Data Source.
The Command Object uses to perform SQL statement or stored procedure to be executed at the
Data Source. The DataReader Object is a stream-based , forward-only, read-only retrieval of
query results from the Data Source, which do not update the data. Finally the DataAdapter
Object , which populate a Dataset Object with results from a Data Source .

DataSet provides a disconnected representation of result sets from the Data Source, and it is
completely independent from the Data Source. DataSet provides much greater flexibility when
dealing with related Result Sets. DataSet consists of a collection of DataTable objects that you
can relate to each other with DataRelation objects. The DataTable contains a collection of
DataRow and DataCoulumn Object which contains Data. The DataAdapter Object provides a
bridge between the DataSet and the Data Source.

In the following section you can see each of the ADO.NET components in details with vb.net
source code.

Advantages of ADO.Net over ADO


ADO stands for ActiveX Data Objects and it relies on COM whereas ADO.NET relies on
managed providers defined by the .NET CLR (Common Language Runtime). ADO.NET
provides consistent access to data sources such as SQL Server, as well as data sources exposed
through OLE DB and XML. While there are similarities between ADO and ADO.NET, the way
they operate and their foundations are quite different. The following are some Advantages of
ADO.Net over ADO in basic level.
A major difference in creating connections with ADO and ADO.NET is that ADO fits all
connections to all types of data sources into a single Connection object. ADO.NET can have
separate Objects that represent connections to different data sources. In ADO.NET you can
create multiple data provider namespaces to connect specifically with a particular data source,
making access faster and more efficient and allowing each namespace to exploit the features of
its targeted data provider.
Dim connection As SqlConnection
connection = New SqlConnection("connetionString")
Dim connection As OleDbConnection
connection = New OleDbConnection("connetionString")

ADO allows you to create client side cursors only whereas ADO.NET gives you the choice of
either using client side or server side cursors.
ADO.NET introduces a new way of getting a single value from a query's results when you
expect only one row and one column to return. The ADO.NET command object has an
ExecuteScalar method which returns the first row and column's value from its associated query.
ADO.Net dataset represents in memory representation of a database. ADO recordsets is merely a
set of rows retrieved from a data source.
ADO recordsets can hold data from one data source at a time. ADO.Net datasets can hold data
from various sources and integrate the data and write it back to one or several data sources.
The ADO.NET Framework supports two models of Data Access Architecture, Connection
Oriented Data Access Architecture and Disconnected Data Access Architecture.
In the case of Data Communication , ADO objects communicate in binary mode while
ADO.NET uses XML for passing the data.
You can find more information on ADO to ADO.NET from the following link :
http://msdn.microsoft.com/en-us/magazine/cc163954.aspx

Connected and Disconnected Data Access


Architecture
The ADO.NET Framework supports two models of Data Access Architecture, Connection
Oriented Data Access Architecture and Disconnected Data Access Architecture.
In Connection Oriented Data Access Architecture the application makes a connection to the Data
Source and then interact with it through SQL requests using the same connection. In these cases
the application stays connected to the database system even when it is not using any Database
Operations.
ADO.Net solves this problem by introduces a new component called Dataset. The DataSet is the
central component in the ADO.NET Disconnected Data Access Architecture. A DataSet is an inmemory data store that can hold multiple tables at the same time. DataSets only hold data and do
not interact with a Data Source. One of the key characteristics of the DataSet is that it has no
knowledge of the underlying Data Source that might have been used to populate it.
Dim ds As New DataSet

In Connection Oriented Data Access, when you read data from a database by using a DataReader
object, an open connection must be maintained between your application and the Data Source.
Unlike the DataReader, the DataSet is not connected directly to a Data Source through a

Connection object when you populate it. It is the DataAdapter that manages connections between
Data Source and Dataset by fill the data from Data Source to the Dataset and giving a
disconnected behavior to the Dataset. The DataAdapter acts as a bridge between the Connected
and Disconnected Objects.
Dim adapter As New SqlDataAdapter("sql", "connection")
Dim ds As New DataSet
adapter.Fill(ds, "Src Table")

By keeping connections open for only a minimum period of time, ADO .NET conserves system
resources and provides maximum security for databases and also has less impact on system
performance.

ADO.NET ConnectionString
Connection String is a normal String representation which contains Database connection
information to establish the connection between Datbase and the Application. The Connection
String includes parameters such as the name of the driver, Server name and Database name , as
well as security information such as user name and password. Data providers use a connection
string containing a collection of parameters to establish the connection with the database.
The .NET Framework provides mainly three data providers: Microsoft SQL Server, OLEDB and
ODBC. Here you can see how to make connection string to these ADO.NET Data Providers.
Microsoft SQL Server Connection String
connetionString ="Data Source = ServerName; Initial Catalog = Databasename; User ID =
UserName; Password=Password"
OLEDB Data Provider Connection String
connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source =
yourdatabasename.mdb;"
ODBC Connection String
connetionString = "Driver = {Microsoft Access Driver (*.mdb)}; DBQ =
yourdatabasename.mdb;"
Note : You have to provide the necessary informations to the Connection String attributes.
In the following section you can see how to these ADO.NET Data Providers establish connection
to the Databse in detail.
SQL Server Connection

OLEDB Connection
ODBC Connection

ADO.NET Data Providers


The .Net Framework includes mainly three Data Providers for ADO.NET. They are the
Microsoft SQL Server Data Provider , OLEDB Data Provider and ODBC Data provider. You can
see from the following links how these Data Providers making connection to the specified data
Sources.
SQL Server Connection
OLEDB Connection
ODBC Connection

The four Objects from the .Net Framework provide the functionality of Data Providers in
ADO.NET. They are Connection Object, Command Object , DataReader Object and
DataAdapter Object. The following link shows in details about these Objects.
Connection
Command
DataReader
DataAdapter

ADO.NET Connection Object


The Connection Object is a part of ADO.NET Data Provider and it is a unique session with the
Data Source. In .Net Framework the Connection Object is Handling the part of physical
communication between the application and the Data Source. Depends on the parameter
specified in the Connection String , ADO.NET Connection Object connect to the specified

Database and open a connection between the application and the Database . When the connection
is established , SQL Commands may be executed, with the help of the Connection Object, to
retrieve or manipulate data in the Database. Once the Database activity is over , Connection
should be closed and release the resources .

In ADO.NET the type of the Connection is depend on what Database system you are working
with. The following are the commonly using the connections in the ADO.NET
SqlConnection
OleDbConnection
OdbcConnection

ADO.NET SQL Server Connection


The SqlConnection Object is Handling the part of physical communication between the
application and the SQL Server Database. An instance of the SqlConnection class in .NET
Framework is supported the Data Provider for SQL Server Database. The SqlConnection
instance takes Connection String as argument and pass the value to the Constructor statement.
When the connection is established , SQL Commands may be executed, with the help of the
Connection Object, to retrieve or manipulate data in the database. Once the Database activities
over , Connection should be closed and release the database resources .
The Close() method in SqlConnection class is used to close the Database Connection. The Close
method rolls back any pending transactions and releases the Connection from the SQL Server
Database.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim connetionString As String


Dim cnn As SqlConnection
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

You have to provide the necessary informations to the Connection String.


connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID =
UserName;
Password
=
Password"
From the above statement replace ServerName, DatabaseName, UserName, Password to the
actual names.

ADO.NET OLEDB Connection


An instance of the OleDbConnection class in .NET Framework is supported the OLEDB Data
Provider. The OleDbConnection instance takes Connection String as argument and pass the value
to the Constructor statement. When the connection is established , SQL Commands may be
executed, with the help of the Connection Object, to retrieve or manipulate data in the database.
Once the Database activities over , Connection should be closed and release the resources . The
Close() method in SqlConnection class is used to close the Database Connection. The Close
method rolls back any pending transactions and releases the Connection from the Database
connected by the OLEDB Data Provider.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As OleDbConnection
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=yourdatabasename.mdb;"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()

Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

You have to provide the necessary informations to the Connection String.


connetionString
=
"Provider
=
Microsoft.Jet.OLEDB.4.0;
Data
Source
=
yourdatabasename.mdb;"
From the above statement replace yourdatabasename.mdb to the actual names.

ADO.NET ODBC Connection


An instance of the OdbcConnection class in .NET Framework is supported the ODBC Data
Provider. The OdbcConnection instance takes Connection String as argument and pass the value
to the Constructor statement. When the connection is established , SQL Commands may be
executed, with the help of the Connection Object, to retrieve or manipulate data in the database.
Once the Database activities over , Connection should be closed and release the resources . The
Close() method in SqlConnection class is used to close the Database Connection. The Close
method rolls back any pending transactions and releases the Connection from the Database
connected by the ODBC Data Provider.
Download Source Code
Print Source Code
Imports System.Data.Odbc
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As OdbcConnection
connetionString = "Driver={Microsoft Access Driver
(*.mdb)};DBQ=yourdatabasename.mdb;"
cnn = New OdbcConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

You have to provide the


connetionString = "Driver
yourdatabasename.mdb;"

necessary informations to the Connection String.


= {Microsoft Access Driver (*.mdb)}; DBQ =

From the above statement replace yourdatabasename.mdb to the actual names.

ADO.NET Command
The Command Object in ADO.NET executes SQL statements and Stored Procedures against the
data source specified in the Connection Object. The Command Object required an instance of a
Connection Object for executing the SQL statements. That is, for retrieving data or execute an
SQL statement against a Data Source , you have to create a Connection Object and open a
connection to the Data Source, and assign the open connection to the connection property of the
Command Object. When the Command Object return result set , a Data Reader is used to retrieve
the result set.

The Command Object has a property called CommandText, which contains a String value that
represents the command that will be executed in the Data Source. When the CommandType
property is set to StoredProcedure, the CommandText property should be set to the name of the
stored procedure.
Click the following links to see some important built in methods uses in the Command Object to
execute the SQL statements.
ExecuteNonQuery
ExecuteReader
ExecuteScalar

ADO.NET ExecuteNonQuery in SqlCommand Object


ExecuteNonQuery() is one of the most frequently used method in SqlCommand Object and is
used for executing statements that do not return result set. ExecuteNonQuery() performs Data
Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating

Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks
like Insert , Update and Delete perform by ExecuteNonQuery().
The following example shows how to use the method ExecuteNonQuery() through SqlCommand
Object.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(Sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
cnn.Close()
MsgBox(" ExecuteNonQuery in SqlCommand executed !!")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID =


UserName;
Password
=
Password"
sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your realtime variables.

ADO.NET ExecuteNonQuery in OleDbCommand


Object
ExecuteNonQuery() is one of the most frequently used method in OleDbCommand Object and is
used for executing statements that do not return result set. ExecuteNonQuery() performs Data
Definition tasks as well as Data Manipulation tasks also. The Data Definition tasks like creating

Stored Procedures and Views perform by ExecuteNonQuery() . Also Data Manipulation tasks
like Insert , Update and Delete perform by ExecuteNonQuery().
The following example shows how to use the method ExecuteNonQuery() through
OleDbCommand Object.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
cmd = New OleDbCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
cnn.Close()
MsgBox(" ExecuteNonQuery in OleDbConnection executed !!")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb


filename;"
sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your realtime variables.

ADO.NET ExecuteScalar in SqlCommand Object


ExecuteScalar() in SqlCommand Object is used for get a single value from Database after its
execution. It executes SQL statements or Stored Procedure and returned a scalar value on first
column of first row in the Result Set. If the Result Set contains more than one columns or rows ,
it takes only the first column of first row, all other values will ignore. If the Result Set is empty it
will return a Null reference.

It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to
ExecuteReader() , ExecuteScalar() uses fewer System resources.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here like Select Count(*) from product"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
MsgBox(" No. of Rows " & count)
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID =


UserName;
Password
=
Password"
sql = "Your SQL Statement Here like Select Count(*) from product"
You have to replace the string with your realtime variables.

ADO.NET ExecuteScalar in OleDbCommand Object


ExecuteScalar() in OleDbCommand Object is used for get a single value from Database after its
execution. It executes SQL statements or Stored Procedure and returned a scalar value on first
column of first row in the Result Set. If the Result Set contains more than one columns or rows ,
it takes only the first column of first row, all other values will ignore. If the Result Set is empty it
will return a Null reference. It is very useful to use with aggregate functions like Count(*) or
Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.
Download Source Code
Print Source Code

Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here like Select Count(*) from product"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
cmd = New OleDbCommand(sql, cnn)
Dim count As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
MsgBox(" No of Rows " & count)
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb


filename;"
sql = "Your SQL Statement Here like Select Count(*) from product"
You have to replace the string with your realtime variables.

ADO.NET ExecuteReader in SqlCommand Object


ExecuteReader() in SqlCommand Object send the SQL statements to Connection Object and
populate a SqlDataReader Object based on the SQL statement. When the ExecuteReader method
in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object.
The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results
from the Data Source, which do not update the data. The SqlDataReader cannot be created
directly from code, they created only by calling the ExecuteReader method of a Command
Object.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
Dim reader As SqlDataReader
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here , like Select * from product"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
reader = cmd.ExecuteReader()
While reader.Read()
MsgBox(reader.Item(0) & " - " & reader.Item(1) & "
reader.Item(2))
End While
reader.Close()
cmd.Dispose()
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

" &

connetionString = "Data Source = ServerName; Initial Catalog = DatabaseName; User ID =


UserName;
Password
=
Password"
sql = "Your SQL Statement Here , like Select * from product"
You have to replace the string with your realtime variables.

ADO.NET ExecuteReader in OleDbCommand Object


ExecuteReader() in OleDbCommand Object send the SQL statements to Connection Object and
populate a OleDbDataReader Object based on the SQL statement. When the ExecuteReader
method in OleDbCommand Object execute , it instantiate a OleDb.OleDbDataReader Object.
The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query
results from the Data Source, which do not update the data. The OleDbDataReader cannot be
created directly from code, they created only by calling the ExecuteReader method of a
Command Object.
Download Source Code
Print Source Code

Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim cnn As OleDbConnection
Dim cmd As OleDbCommand
Dim sql As String
Dim reader As OleDbDataReader
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here like Select * from product"
cnn = New OleDbConnection(connetionString)
Try
cnn.Open()
cmd = New OleDbCommand(sql, cnn)
reader = cmd.ExecuteReader()
While reader.Read()
MsgBox(reader.Item(0) & " - " & reader.Item(1) & "
reader.Item(2))
End While
reader.Close()
cmd.Dispose()
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

" &

connetionString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = Your mdb


filename;"
sql
=
"Your
SQL Statement
Here
like
Select
* from
product"
You have to replace the string with your realtime variables.

How to ADO.NET DataReader


DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query
results from the Data Source, which do not update the data. The DataReader cannot be created
directly from code, they created only by calling the ExecuteReader method of a Command
Object.

DataReader = Command.ExecuteReader()
DataReader Object provides a connection oriented data access to the data Sources. A Connection
Object can contain only one DataReader at a time and the connection in the DataReader remains
open and cannot be used for any other purpose while data is being accessed. When started to read
from a DataReader it should always be open and positioned prior to the first record. The Read()
method in the DataReader is used to read the rows from DataReader and it always moves
forward to a new valid row, if any row exist .
DataReader.Raed()
There are two types of DataReader in ADO.NET. They are SqlDataReader and the
OleDbDataReader. The System.Data.SqlClient and System.Data.OleDb are containing these
DataReaders respectively. From the following link you can see in details about these classes.
SqlDataReader
OleDbDataReader

How to ADO.NET SqlDataReader


SqlDataReader Object provides a connection oriented data access to the SQL Server data
Sources. ExecuteReader() in the SqlCommand Object send the SQL statements to SqlConnection
Object and populate a SqlDataReader Object based on the SQL statement.
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
When the ExecuteReader method in SqlCommand Object execute , it instantiate a
SqlClient.SqlDataReader Object. When started to read from a DataReader it should always be
open and positioned prior to the first record. The Read() method in the DataReader is used to
read the rows from DataReader and it always moves forward to a new valid row, if any row
exist .
SqlDataReader.Read()

Download Source Code


Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here , like Select * from product"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
MsgBox(sqlReader.Item(0) & " - " & sqlReader.Item(1) & "
" & sqlReader.Item(2))
End While
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql = "Your SQL Statement Here , like Select * from product"
You have to replace the string with your realtime variables.

How to ADO.NET OleDbDataReader


OleDbDataReader Object provides a connection oriented data access to the OLEDB Data
Sources. ExecuteReader() in the OleDbCommand Object send the SQL statements to
OleDbConnection Object and populate an OleDbDataReader Object based on the SQL
statement.
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()

When the ExecuteReader method in OleDbCommand Object execute , it instantiate an


OleDb.OleDbDataReader Object. When started to read from an OleDbDataReader it should
always be open and positioned prior to the first record. The Read() method in the
OleDbDataReader is used to read the rows from OleDbDataReader and it always moves forward
to a new valid row, if any row exist .
OleDbDataReader.Read()
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim oledbCnn As OleDbConnection
Dim oledbCmd As OleDbCommand
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here like Select * from product"
oledbCnn = New OleDbConnection(connetionString)
Try
oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
While oledbReader.Read
MsgBox(oledbReader.Item(0) & " - " & oledbReader.Item(1) & "
- " & oledbReader.Item(2))
End While
oledbReader.Close()
oledbCmd.Dispose()
oledbCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


sql
=
"Your
SQL Statement
Here
like
Select
* from
product"
You have to replace the string with your realtime variables.

How to Multiple Result Sets in ADO.NET


The DataReader Object is a stream-based , forward-only, read-only retrieval of query results
from the Data Source, which do not update the data. When the ExecuteReader method in
SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object.
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
In some situations we need to pass multiple SQL statements to the Command Object. In this
situations the SqlDataReader returns multiple ResultSets also. For retrieveing multiple
ResultSets from SqlDataReader we use the NextResult() method of the SqlDataReader.
SqlDataReader.NextResult()
In the following source code demonstrating how to get multiple result sets from SqlDataReader()
.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select top 2 * from product; select top 2 * from ordermaster;
select top 2 * from orderdetails"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While sqlReader.Read()
MsgBox("From first SQL - " & sqlReader.Item(0) & "
sqlReader.Item(1))
End While

" &

sqlReader.NextResult()
While sqlReader.Read()
MsgBox("From second SQL sqlReader.Item(1))
End While
sqlReader.NextResult()

" & sqlReader.Item(0) & "

" &

While sqlReader.Read()
MsgBox("From third SQL sqlReader.Item(1))
End While

" & sqlReader.Item(0) & "

" &

sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql = "Select top 2 * from product; select top 2 * from ordermaster; select top 2 * from
orderdetails"
You have to replace the string with your realtime variables.

Schema Informations from SqlDataReader


The SqlDataReader Object is a stream-based , forward-only, read-only retrieval of query results
from the Data Source, which do not update the data. When the ExecuteReader method in
SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object.
DDim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
While a SqlDataReader is open, you can retrieve schema information about the current result set
using the GetSchemaTable method. GetSchemaTable returns a DataTable object populated with
rows and columns that contain the schema information for the current result set.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
sqlCnn = New SqlConnection(connetionString)

Try

sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
Dim schemaTable As DataTable = sqlReader.GetSchemaTable()
Dim row As DataRow
Dim column As DataColumn

For Each row In schemaTable.Rows


For Each column In schemaTable.Columns
MsgBox(String.Format("{0} = {1}", column.ColumnName,
row(column)))
Next
Next
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql
=
"Select
*
from
product"
You have to replace the string with your realtime variables.

Schema Informations from OleDbDataReader


The OleDbDataReader Object is a stream-based , forward-only, read-only retrieval of query
results from the Data Source, which do not update the data. When the ExecuteReader method in
oledbCmd Object execute , it instantiate a OleDb.OleDbDataReader Object.
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
While a OleDbDataReader is open, you can retrieve schema information about the current result
set using the GetSchemaTable method. GetSchemaTable returns a DataTable object populated
with rows and columns that contain the schema information for the current result set.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim oledbCnn As OleDbConnection

Dim oledbCmd As OleDbCommand


Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here like Select * from product"
oledbCnn = New OleDbConnection(connetionString)
Try
oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
Dim schemaTable As DataTable = oledbReader.GetSchemaTable()
Dim row As DataRow
Dim column As DataColumn
For Each row In schemaTable.Rows
For Each column In schemaTable.Columns
MsgBox(String.Format("{0} = {1}", column.ColumnName,
row(column)))
Next
Next
oledbReader.Close()
oledbCmd.Dispose()
oledbCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


sql
=
"Your
SQL Statement
Here
like
Select
* from
product"
You have to replace the string with your realtime variables.

What is DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter provides the communication
between the Dataset and the Datasource. We can use the DataAdapter in combination with the
DataSet Object. That is these two objects combine to enable both data access and data
manipulation capabilities.

The DataAdapter can perform Select , Insert , Update and Delete SQL operations in the Data
Source. The Insert , Update and Delete SQL operations , we are using the continuation of the
Select command perform by the DataAdapter. That is the DataAdapter uses the Select statements
to fill a DataSet and use the other three SQL commands (Insert, Update, delete) to transmit
changes back to the Database. From the following links describe how to use SqlDataAdapter and
OleDbDataAdapter in detail.
SqlDataAdapter
OleDbDataAdapter

What is SqlDataAdapter
SqlDataAdapter is a part of the ADO.NET Data Provider and it resides in the
System.Data.SqlClient namespace. SqlDataAdapter provides the communication between the
Dataset and the SQL database. We can use SqlDataAdapter Object in combination with Dataset
Object.
Dim adapter As New SqlDataAdapter
The SqlDataAdapter Object and DataSet objects are combine to perform both data access and
data manipulation operations in the SQL Server Database. When the user perform the SQL
operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly
affect the Database, until the user invoke the Update method in the SqlDataAdapter.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sqlCmd As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim i As Integer

Dim sql As String


connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserNamePassword=Password"
sql = "Select * from product"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
sqlCmd = New SqlCommand(sql, sqlCnn)
adapter.SelectCommand = sqlCmd
adapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0) & "
ds.Tables(0).Rows(i).Item(1))
Next
adapter.Dispose()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

--

" &

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql
=
"Select
*
from
product"
You have to replace the string with your realtime variables.

What is OleDbDataAdapter
OleDbDataAdapter is a part of the ADO.NET Data Provider and it resides in the
System.Data.OleDb namespace. OleDbDataAdapter provides the communication between the
Dataset and the OleDb Data Sources. We can use OleDbDataAdapter Object in combination with
Dataset Object.
The OleDbDataAdapter Object and DataSet objects are combine to perform both Data Access
and Data Manipulation operations in the OleDb Data Sources. When the user perform the SQL
operations like Select , Insert etc. in the data containing in the Dataset Object , it won't directly
affect the Database, until the user invoke the Update method in the OleDbDataAdapter.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim
Dim
Dim
Dim
Dim
Dim

connetionString As String
oledbCnn As OleDbConnection
oledbAdapter As OleDbDataAdapter
ds As New DataSet
sql As String
i As Integer

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your


mdb filename;"
sql = "Your SQL Statement Here like Select * from product"
oledbCnn = New OleDbConnection(connetionString)
Try
oledbCnn.Open()
oledbAdapter = New OleDbDataAdapter(sql, oledbCnn)
oledbAdapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " &
ds.Tables(0).Rows(i).Item(1))
Next
oledbAdapter.Dispose()
oledbCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


sql
=
"Your
SQL Statement
Here
like
Select
* from
product"
You have to replace the string with your realtime variables.

Vb.NET ExecuteReader and ExecuteNonQuery


ExecuteReader : ExecuteReader used for getting the query results as a DataReader object. It is
readonly forward only retrieval of records and it uses select command to read through the table
from the first to the last.
Dim reader As SqlDataReader
reader = Command.ExecuteReader()
While reader.Read()
MsgBox(reader.Item(0))
End While
reader.Close()

ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data.
It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes
the command and returns the number of rows affected.

Dim retValue As Integer


Command = New SqlCommand(Sql, Connection)
retValue = Command.ExecuteNonQuery()

What is ADO.NET Dataset


The ADO.NET DataSet contains DataTableCollection and their DataRelationCollection . It
represents a collection of data retrieved from the Data Source. We can use Dataset in
combination with DataAdapter class. The DataSet object offers a disconnected data source
architecture. The Dataset can work with the data it contain, without knowing the source of the
data coming from. That is , the Dataset can work with a disconnected mode from its Data
Source . It gives a better advantage over DataReader , because the DataReader is working only
with the connection oriented Data Sources.

The Dataset contains the copy of the data we requested. The Dataset contains more than one
Table at a time. We can set up Data Relations between these tables within the DataSet. The data
set may comprise data for one or more members, corresponding to the number of rows.

The DataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method
of the DataAdapter for populating data in a Dataset. The DataSet can be filled either from a data
source or dynamically. A DataSet can be saved to an XML file and then loaded back into
memory very easily. The following links shows more information of Dataset in details.

How to Dataset with Sql Server


The DataSet contains the copy of the data we requested through the SQL statement. We can use
Dataset in combination with SqlDataAdapter class . The SqlDataAdapter object allows us to
populate Data Tables in a DataSet. We can use Fill method in the SqlDataAdapter for populating
data in a Dataset.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim i As Integer
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()

command.Dispose()
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0) & "
ds.Tables(0).Rows(i).Item(1))
Next

--

" &

Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

How to Dataset with OLEDB Data Source


The DataSet contains the copy of the data we requested through the SQL statement. We can use
Dataset in combination with OleDbDataAdapter class . The OleDbDataAdapter object allows us
to populate Data Tables in a DataSet. We can use Fill method in the OleDbDataAdapter for
populating data in a Dataset.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here"
connection = New OleDbConnection(connetionString)
Try
connection.Open()
oledbAdapter = New OleDbDataAdapter(sql, connection)
oledbAdapter.Fill(ds)
oledbAdapter.Dispose()
connection.Close()

For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0) & "
ds.Tables(0).Rows(i).Item(1))
Next
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

--

" &

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

Search Tables in a Dataset Sql Server


The DataSet contains DataTableCollection and their DataRelationCollection. The
DataTableCollection contains zero or more DataTable objects. The Dataset may comprise data
for one or more members, corresponding to the number of rows. The SqlDataAdapter object
allows us to populate DataTables in a DataSet.
In some situations we have to find how many tables inside the Dataset Object contains . The
following VB.NET source code shows how to find the tables inside the Dataset.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim tables As DataTable
Dim i As Integer
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here"
connection = New SqlConnection(connetionString)
Try

connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "SQL Temp Table")

adapter.Dispose()
command.Dispose()
connection.Close()
For Each tables In ds.Tables
MsgBox(tables.TableName)
Next
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

Search Tables in a Dataset OLEDB Data Source


The DataSet contains DataTableCollection and their DataRelationCollection. The
DataTableCollection contains zero or more DataTable objects. The data inside Table is in the
form of Rows and Columns . The OleDbDataAdapter object allows us to populate DataTables in
a DataSet.
In some situations we have to find how many tables inside the Dataset Object contains . The
following VB.NET source code shows how to find the tables inside the Dataset.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim ds As New DataSet
Dim sql As String
Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here"
connection = New OleDbConnection(connetionString)
Try
connection.Open()

oledbAdapter = New OleDbDataAdapter(sql, connection)


oledbAdapter.Fill(ds, "OLEDB Temp Table")
oledbAdapter.Dispose()
connection.Close()
For i = 0 To ds.Tables.Count - 1
MsgBox(ds.Tables(i).TableName)
Next
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

Dataset table row count in SQL Server


The DataSet contains copy of the data we requested through the SQL statement. The DataSet
consists of DataTableCollection and their DataRelationCollection. The DataTableCollection
contains zero or more DataTable objects. 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 Dataset.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here"
connection = New SqlConnection(connetionString)
Try

connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "SQL Temp Table")

adapter.Dispose()
command.Dispose()
connection.Close()
MsgBox("Number of row(s)

" & ds.Tables(0).Rows.Count)

Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

Dataset table row count - OLEDB Data Source


The DataSet contains copy of the data we requested through the SQL statement. The DataSet
consists of DataTableCollection and their DataRelationCollection. The DataTableCollection
contains zero or more DataTable objects. The data inside Table is in the form of Rows and
Columns . The following VB.NET source code shows how to find the number of rows in a table
that resides in the Dataset from OLEDB Data Source.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here"
connection = New OleDbConnection(connetionString)
Try
connection.Open()
oledbAdapter = New OleDbDataAdapter(sql, connection)
oledbAdapter.Fill(ds, "OLEDB Temp Table")
oledbAdapter.Dispose()
connection.Close()
MsgBox("number of Row(s)

" & ds.Tables(0).Rows.Count)

Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

How to find column definition - Sql Server


Dataset represents a collection of data retrieved from the Data Source. The Dataset can work
with the data it contains, without knowing the source of the data coming from. The
SqlDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in
the SqlDataAdapter for populating data in a Dataset. The Dataset can contains more than one
Table at a time. The data inside Table is in the form of Rows and Columns .
In some situations we have to find the column headers in a DataTable. There is a
ColumnsCollection object in the Datatable hold the column Definitions.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim dt As DataTable
Dim column As DataColumn
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Your SQL Statement Here"
connection = New SqlConnection(connetionString)
Try

connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "SQL Temp Table")
adapter.Dispose()
command.Dispose()
connection.Close()

dt = ds.Tables(0)
For Each column In dt.Columns
MsgBox(column.ColumnName)
Next
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

How to find column definition - OLEDB Data Source


Dataset represents a collection of data retrieved from the Data Source.. The OleDbDataAdapter
object allows us to populate DataTable in a DataSet. We can use Fill method in the
OleDbDataAdapter for populating data in a Dataset. The Dataset 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.
In some situations we have to find the column headers in a DataTable. There is a
ColumnsCollection object in the Datatable hold the column Definitions.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim ds As New DataSet
Dim dt As DataTable
Dim sql As String
Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
sql = "Your SQL Statement Here"
connection = New OleDbConnection(connetionString)

Try

connection.Open()
oledbAdapter = New OleDbDataAdapter(sql, connection)
oledbAdapter.Fill(ds, "OLEDB Temp Table")
oledbAdapter.Dispose()
connection.Close()

dt = ds.Tables(0)
For i = 0 To dt.Columns.Count - 1
MsgBox(dt.Columns(i).ColumnName)
Next
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

How to create DataSet without Databse


Dataset represents a collection of data retrieved from the Data Source. The DataSet contains
DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or
more DataTable objects. The data set may comprise data for one or more members,
corresponding to the number of rows. We can fill the data in Dataset without calling SQL
statements. For that we manually create a DataTable and add data in it.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim ds As New DataSet
Dim dt As DataTable
Dim dr As DataRow
Dim idCoulumn As DataColumn
Dim nameCoulumn As DataColumn
Dim i As Integer
dt = New DataTable()
idCoulumn = New DataColumn("ID", Type.GetType("System.Int32"))
nameCoulumn = New DataColumn("Name", Type.GetType("System.String"))
dt.Columns.Add(idCoulumn)
dt.Columns.Add(nameCoulumn)
dr = dt.NewRow()

dr("ID") = 1
dr("Name") = "Name1"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr("ID") = 2
dr("Name") = "Name2"
dt.Rows.Add(dr)
ds.Tables.Add(dt)
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0) & "
ds.Tables(0).Rows(i).Item(1))
Next i

--

" &

End Sub
End Class

How to multiple tables in Dataset - Sql Server


The DataSet contains DataTableCollection and their DataRelationCollection. The
DataTableCollection contains zero or more DataTable objects. The SqlDataAdapter object allows
us to populate DataTables in a DataSet. We can use Fill method in the SqlDataAdapter for
populating data in a Dataset.
We can populate Dataset with more than one table at a time using SqlDataAdapter Object . The
following VB.NET source code shows how to a single SqlDataAdapter fill Dataset with multiple
tables.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim i As Integer
Dim firstSql As String
Dim secondSql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
firstSql = "Your First SQL Statement Here"
secondSql = "Your Second SQL Statement Here"
connection = New SqlConnection(connetionString)

Try

connection.Open()
command = New SqlCommand(firstSql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "First Table")
adapter.SelectCommand.CommandText = secondSql
adapter.Fill(ds, "Second Table")
adapter.Dispose()
command.Dispose()
connection.Close()

'retrieve first table data


For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0) & "
ds.Tables(0).Rows(i).Item(1))
Next
'retrieve second table data
For i = 0 To ds.Tables(1).Rows.Count - 1
MsgBox(ds.Tables(1).Rows(i).Item(0) & "
ds.Tables(1).Rows(i).Item(1))
Next

--

" &

--

" &

Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
sql
=
"Your
SQL
Statement
Here"
You have to replace the string with your real time variables.

How to multiple tables in Dataset - OLEDB Data


Source
The DataSet contains DataTableCollection and their DataRelationCollection. The
DataTableCollection contains zero or more DataTable objects. The OleDbDataAdapter object
allows us to populate DataTables in a DataSet. We can use Fill method in the OleDbDataAdapter
for populating data in a Dataset. We can populate Dataset with more than one table at a time
using OleDbDataAdapter Object . The following VB.NET source code shows how to a single
OleDbDataAdapter fill Dataset with multiple tables.
Download Source Code
Print Source Code
Imports System.Data.OleDb

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim ds As New DataSet
Dim firstSql As String
Dim secondSql As String
Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
firstSql = "Your First SQL Statement Here"
secondSql = "Your Second SQL Statement Here"
connection = New OleDbConnection(connetionString)
Try
connection.Open()
oledbAdapter = New OleDbDataAdapter(firstSql, connection)
oledbAdapter.Fill(ds, "First Table")
oledbAdapter.SelectCommand.CommandText = secondSql
oledbAdapter.Fill(ds, "Second Table")
oledbAdapter.Dispose()
connection.Close()
'retrieve first table data
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0) & " -- " &
ds.Tables(0).Rows(i).Item(1))
Next
'retrieve second table data
For i = 0 To ds.Tables(1).Rows.Count - 1
MsgBox(ds.Tables(1).Rows(i).Item(0) & " -- " &
ds.Tables(1).Rows(i).Item(1))
Next
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


firstSql
=
"Your
First
SQL
Statement
Here"
secondSql
=
"Your
Second
SQL
Statement
Here"
You have to replace the string with your real time variables.

How to add relations between tables in a Dataset


The DataSet contains DataTableCollection and their DataRelationCollection. The
DataSet.Relations property is an instance of the DataRelationsCollection Object. We can create
parent child data relations between DataTable using Datarelation Object. We can relate one or
more column from different tables using DataRelation Object . The columns involved in the
DataRelation should be identical data types. That is the parent and child column should be
similar Data Types.

Download Source Code


Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim firstSql As String
Dim secondSql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
firstSql = "Your First SQL Statement Here"
secondSql = "Your Second SQL Statement Here"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(firstSql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Table1")
adapter.SelectCommand.CommandText = secondSql
adapter.Fill(ds, "Table2")
adapter.Dispose()
command.Dispose()
connection.Close()
'creating data relations
Dim relation As DataRelation
Dim table1Column As DataColumn
Dim table2Column As DataColumn
'retrieve column
table1Column = ds.Tables("Table1").Columns(0)
table2Column = ds.Tables("table2").Columns(0)
'relating tables
relation = New DataRelation("relation", table1Column,
table2Column)
'assign relation to dataset
ds.Relations.Add(relation)
MsgBox("Data relation completed")
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
firstSql
=
"Your
First
SQL
Statement
Here"
secondSql
=
"Your
Second
SQL
Statement
Here"

You have to replace the string with your real time variables.

How to merge tables in a Dataset - Sql Server


The DataSet contains copy of the data we requested through the SQL statement. The
SqlDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method in
the SqlDataAdapter for populating data in a Dataset. We can populate Dataset with more than
one table at a time using SqlDataAdapter Object. The DataTableCollection contains zero or more
DataTable objects.
In some situation we want to combine the result of multiple SQL query as a single result set. In
that case we can use the Dataset's Merge method for doing this. The tables involved in the merge
should be identical, that is the columns are similar data types .
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim dt As DataTable
Dim firstSql As String
Dim secondSql As String
Dim i As Integer
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
firstSql = "Your First SQL Statement Here"
secondSql = "Your Second SQL Statement Here"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(firstSql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Table(0)")
adapter.SelectCommand.CommandText = secondSql
adapter.Fill(ds, "Table(1)")
adapter.Dispose()
command.Dispose()
connection.Close()
ds.Tables(0).Merge(ds.Tables(1))
dt = ds.Tables(0)
For i = 0 To dt.Rows.Count - 1
MsgBox(dt.Rows(i).Item(0) & "

--

" & dt.Rows(i).Item(1))

Next
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User


ID=UserName;Password=Password"
firstSql
=
"Your
First
SQL
Statement
Here"
secondSql
=
"Your
Second
SQL
Statement
Here"
You have to replace the string with your real time variables.

How to merge tables in a Dataset - OLEDB Data


Source
The DataSet contains copy of the data we requested through the SQL statement. The
OleDbDataAdapter object allows us to populate DataTable in a DataSet. We can use Fill method
in the OleDbDataAdapter for populating data in a Dataset. We can populate Dataset with more
than one table at a time using OleDbDataAdapter Object. The DataTableCollection contains zero
or more DataTable objects. In some situation we want to combine the result of multiple SQL
query results as a single result set. In that case we can use the Dataset's 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.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim ds1 As New DataSet
Dim ds2 As New DataSet
Dim dt As DataTable
Dim firstSql As String
Dim secondSql As String
Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
firstSql = "Your First SQL Statement Here"
secondSql = "Your Second SQL Statement Here"
connection = New OleDbConnection(connetionString)
Try
connection.Open()

oledbAdapter = New OleDbDataAdapter(firstSql, connection)


oledbAdapter.Fill(ds1, "First Table")
oledbAdapter.SelectCommand.CommandText = secondSql
oledbAdapter.Fill(ds2, "Second Table")
oledbAdapter.Dispose()
connection.Close()
ds1.Tables(0).Merge(ds2.Tables(0))
dt = ds1.Tables(0)
For i = 0 To dt.Rows.Count - 1
MsgBox(dt.Rows(i).Item(0) & "
Next

--

" & dt.Rows(i).Item(1))

Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"


firstSql
=
"Your
First
SQL
Statement
Here"
secondSql
=
"Your
Second
SQL
Statement
Here"
You have to replace the string with your real time variables.

How to populate a combo box from a dataset in


VB.Net

The DataSet consists of a collection of DataTable objects that you can relate to each other with
DataRelation objects. The VB.Net SqlDataAdapter object allows us to populate Data Tables in a
DataSet. Also we can populate a combo box from a dataset values.
ComboBox1.DataSource = ds.Tables(0)

ComboBox1.ValueMember = "au_id"
ComboBox1.DisplayMember = "au_lname"

The following VB.Net program fetch the values from database and store it in a dataset and later
bind to a combobox.
Download Source Code
Print Source Code
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim connetionString As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim i As Integer = 0
Dim sql As String = Nothing
connetionString = "Data Source=ServerName;Initial
Catalog=databasename;User ID=userid;Password=yourpassword"
sql = "select au_id,au_lname from authors"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.ValueMember = "au_id"
ComboBox1.DisplayMember = "au_lname"
Catch ex As Exception
MessageBox.Show("Can not open connection ! ")
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
MsgBox(ComboBox1.Text + " -- " + ComboBox1.SelectedValue)
End Sub
End Class

how many tables exist in a database - VB.NET


A table is responsible for storing data in the database. A table is a set of data elements that is
organized using a model of vertical columns and horizontal rows.A database is made up of many
linked tables of rows and columns, each containing specific data.
In many situations you should find the no. of tables exist in your database. Everything about your
SQL Server database is stored in its system tables.
Select DISTINCT(name) FROM sys.Tables

Returns a row for each table object, currently only with sys.objects.type = U. System tables
should not be altered directly by any user
Download Source Code
Print Source Code
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim tables As DataTable
Dim i As Integer
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select DISTINCT(name) FROM sys.Tables"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0))
Next

Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

Dataadapter with dataset - sql sever


SqlDataAdapter provides the communication between the Dataset and the Data Source with the
help of SqlConnection Object . The SqlConnection Object has no information about the data it
retrieves . Similarly a Dataset has no knowledge of the Data Source where the data coming from.
So the SqlDataAdapter manage the communication between these two Objects.
The SqlDataAdapter object allows us to populate Data Tables in a DataSet. We can use Fill
method of the SqlDataAdapter for populating data in a Dataset. The following source code shows
a simple program that uses SqlDataAdapter to retrieve data from Data Source with the help of
SqlConnection object and populate the data in a Dataset.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim i As Integer
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Try
connection.Open()
adapter = New SqlDataAdapter("Your SQL Statement Here",
connection)
adapter.Fill(ds)
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(1))
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter with dataset - OLEDB Data Source


OleDbDataAdapter provides the communication between the Dataset and the Data Source with
the help of OleDbConnection Object . The OleDbConnection Object has no information about
the data it retrieves . Similarly a Dataset has no knowledge of the Data Source where the data
coming from. So the OleDbDataAdapter manage the communication between these two Objects.
The OleDbDataAdapter object allows us to populate Data Tables in a DataSet. We can use Fill
method of the OleDbDataAdapter for populating data in a Dataset. The following source code
shows a simple program that uses OleDbDataAdapter to retrieve data from Data Source with the
help of OleDbConnection object and populate the data in a Dataset.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim ds As New DataSet
Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
connection = New OleDbConnection(connetionString)
Try
connection.Open()
oledbAdapter = New OleDbDataAdapter("Your SQL Statement Here")
oledbAdapter.Fill(ds)
oledbAdapter.Dispose()
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0))
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter SelectCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. SqlDataAdapter provides the
communication between the Dataset and the Data Source with the help of SqlConnection
Object .The SqlDataAdapter works with the DataSet to provide a disconnected data retrieval
mechanism.

The SelectCommand property of the SqlDataAdapter is a Command object that retrieves data
from the data source. The following program shows the SqlDataAdapter using its
SelectCommand property to retrieve the data from the Data Source.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim i As Integer
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Try
connection.Open()
adapter.SelectCommand = New SqlCommand("Your SQL Statement Here",
connection)
adapter.Fill(ds)
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(1))
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter SelectCommand - OLEDB Data Source


OleDbDataAdapter is a part of the ADO.NET Data Provider. OleDbDataAdapter provides the
communication between the Dataset and the Data Source with the help of OleDbConnection
Object. The OleDbDataAdapter works with the DataSet to provide a disconnected data retrieval
mechanism.
The SelectCommand property of the OleDbDataAdapter is a Command object that retrieves data
from the data source. The following program shows the OleDbDataAdapter using its
SelectCommand property to retrieve the data from the Data Source.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Dim ds As New DataSet
Dim i As Integer
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
connection = New OleDbConnection(connetionString)
Try
connection.Open()
oledbAdapter.SelectCommand = New OleDbCommand("Your SQL Statement
Here", connection)
oledbAdapter.Fill(ds)
oledbAdapter.Dispose()
connection.Close()
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(0))
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter InsertCommand - Sql Server


SqlDataAdapter provides the communication between the Dataset and the Data Source with the
help of SqlConnection Object . The InsertCommand in SqlDataAdapter Object manages to insert
the data in the specified Data Source .
In the following Source Code shows how to insert data in the Data Source using SqlDataAdapter
and SqlCommand object. Open a connection to the Data Source with the help of SqlConnection
object and create a SqlCommand object with insert SQL statement, and assign the SqlCommand
to the SqlDataAdapter's InsertCommand.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)

sql = "insert into product (Product_id,Product_name,Product_price)


values(7,'Product7',700)"
Try
connection.Open()
adapter.InsertCommand = New SqlCommand(sql, connection)
adapter.InsertCommand.ExecuteNonQuery()
MsgBox("Row inserted !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter InsertCommand - OLEDB Data Source


OleDbDataAdapter provides the communication between the Dataset and the Data Source with
the help of OleDbConnection Object . The InsertCommand in OleDbDataAdapter Object
manages to insert the data in the specified Data Source .
In the following Source Code shows how to insert data in the Data Source using
OleDbDataAdapter and OleDbCommand object. Open a connection to the Data Source with the
help of OleDbConnection object and create an OleDbCommand object with insert SQL
statement, and assign the OleDbCommand to the SqlDataAdapter's InsertCommand.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
connection = New OleDbConnection(connetionString)
sql = "insert into user values('user1','password1')"
Try
connection.Open()
oledbAdapter.InsertCommand = New OleDbCommand(sql, connection)
oledbAdapter.InsertCommand.ExecuteNonQuery()
MsgBox("Row(s) Inserted !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter UpdateCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the
UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the
database with the data modifications, that are run on a DataSet object.
The following code samples that demonstrate how to use the SqlDataAdapter object to update a
SQL Server database using UpdateCommand properties in SqlDataAdapter.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
sql = "update product set product_price = 1001 where Product_name
='Product7'"
Try
connection.Open()
adapter.UpdateCommand = connection.CreateCommand
adapter.UpdateCommand.CommandText = sql
adapter.UpdateCommand.ExecuteNonQuery()
MsgBox("Row updated !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter UpdateCommand - OLEDB Data Source


OleDbDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the
UpdateCommand, and the DeleteCommand properties of the OleDbDataAdapter object update
the Data Source with the data modifications that are run on a DataSet object.
The following code samples that demonstrate how to use the OleDbDataAdapter object to update
an OLEDB Data Source using UpdateCommand properties in OleDbDataAdapter.
Download Source Code
Print Source Code

Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
connection = New OleDbConnection(connetionString)
sql = "update Users set Password = 'new password' where UserID =
'user1'"
Try
connection.Open()
oledbAdapter.UpdateCommand = connection.CreateCommand
oledbAdapter.UpdateCommand.CommandText = sql
oledbAdapter.UpdateCommand.ExecuteNonQuery()
MsgBox("Row(s) Updated !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter DeleteCommand - Sql Server


SqlDataAdapter is a part of the ADO.NET Data Provider. The InsertCommand, the
UpdateCommand, and the DeleteCommand properties of the SqlDataAdapter object update the
database with the data modifications, that are run on a DataSet object.
The following code samples that demonstrate how to use the SqlDataAdapter object to update a
SQL Server database using UpdateCommand properties in SqlDataAdapter.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As New SqlDataAdapter
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
sql = "delete product where Product_name ='Product7'"
Try
connection.Open()
adapter.DeleteCommand = connection.CreateCommand

adapter.DeleteCommand.CommandText = sql
adapter.DeleteCommand.ExecuteNonQuery()
MsgBox("Row(s) deleted !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter DeleteCommand - OLEDB Data Source


OleDbDataAdapter is a part of the ADO.NET Data Provider. The OleDbDataAdapter works with
the DataSet to provide a disconnected data retrieval mechanism. The InsertCommand,
UpdateCommand, and DeleteCommand properties of the OleDbDataAdapter are Command
objects that manage updates to the specified data source according to modifications.
The following Source Code shows how to perform delete data from a database using
DeleteCommand property of OleDbDataAdapter.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As New OleDbDataAdapter
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
connection = New OleDbConnection(connetionString)
sql = "delete from Users where UserID = 'user1'"
Try
connection.Open()
oledbAdapter.DeleteCommand = connection.CreateCommand
oledbAdapter.DeleteCommand.CommandText = sql
oledbAdapter.DeleteCommand.ExecuteNonQuery()
MsgBox("Row(s) Deleted !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter with CommandBuilder - Sql Server


The DataAdapter is a part of the ADO.NET Data Provider. ADO.NET DataAdapter is used to
manage four separate Command objects. The InsertCommand, the UpdateCommand, and the
DeleteCommand properties of the SqlDataAdapter object update the database with the data
modifications that are run on a DataSet object. The SqlCommand objects that are assigned to
these properties can be created manually in code or automatically generated by using the
SqlCommandBuilder object.
The SqlCommandBuilder opens the Connection associated with the DataAdapter and makes a
round trip to the server each and every time it's asked to construct the action queries. It closes the
Connection when it's done. The following Source Code demonstrate how to use the
SqlDataAdapter object to update a SQL Server database with data modifications that are run on a
DataSet object that is populated with data from a table in the database using
SqlCommandBuilder object.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim sql As String
Dim i As Int32
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
sql = "select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
cmdBuilder = New SqlCommandBuilder(adapter)
adapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
ds.Tables(0).Rows(i).Item(2) = ds.Tables(0).Rows(i).Item(2) +
100
Next
adapter.Update(ds.Tables(0))
connection.Close()
MsgBox("Data updated ! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter with CommandBuilder - OLEDB


The OleDbDataAdapter is a part of the ADO.NET Data Provider. OleDbDataAdapter is used to
manage four separate Command objects. The InsertCommand, the UpdateCommand, and the
DeleteCommand properties of the OleDbDataAdapter object update the database with the data
modifications that are run on a DataSet object. The OleDbCommand objects that are assigned to
these properties can be created manually in code or automatically generated by using the
OleDbCommandBuilder object.
The OleDbCommandBuilder opens the Connection associated with the OleDbDataAdapter and
makes a round trip to the server each and every time it's asked to construct the action queries. It
closes the Connection when it's done. The following Source Code demonstrate how to use the
OleDbDataAdapter object to update a OLEDB Data Source with data modifications that are run
on a DataSet object that is populated with data from a table in the database using
OleDbCommandBuilder object.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim oledbCmdBuilder As OleDbCommandBuilder
Dim ds As New DataSet
Dim i As Integer
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
connection = New OleDbConnection(connetionString)
sql = "select * from tblUsers"
Try
connection.Open()
oledbAdapter = New OleDbDataAdapter(sql, connection)
oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter)
oledbAdapter.Fill(ds)
For i = 0 To ds.Tables(0).Rows.Count - 1
ds.Tables(0).Rows(i).Item(2) = "neweamil@email.com"
Next
oledbAdapter.Update(ds.Tables(0))
connection.Close()
MsgBox("Email address updates !")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter with DataGridView - Sql Server


SqlDataAdapter provides the communication between the Dataset and the Data Source with the
help of SqlConnection Object . The SqlConnection Object has no information about the data it
retrieves . Similarly a Dataset has no knowledge of the Data Sourcewhere the data coming from.
So the SqlDataAdapter manage the communication between these two Objects. The
TableMapping Collections help the SqlDataAdapter to do this task.
The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the
SqlDataAdapter object update the database with the data modifications that are run on a DataSet
object. The following source code demonstrate how to update a Dataset through SqlDataAdapter
using a DataGridView. For running this source code , open a new VB.NET project and drag two
buttons and a DataGridView in the default form1 and copy and paste the following Source Code.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim cmdBuilder As SqlCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim sql As String
Dim i As Int32
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
connection = New SqlConnection(connetionString)
Sql = "select * from Product"
Try
connection.Open()
adapter = New SqlDataAdapter(Sql, connection)
adapter.Fill(ds)
connection.Close()
DataGridView1.Data Source= ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)

End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Dataadapter with DataGridView - OLEDB


OleDbDataAdapter provides the communication between the Dataset and the OLEDB Data
Source with the help of OleDbConnection Object . The OleDbConnection Object has no
information about the data it retrieves . Similarly a Dataset has no knowledge of the Data Source
where the data coming from. So the OleDbDataAdapter manage the communication between
these two Objects. The TableMapping Collection help the OleDbDataAdapter to do this task.
The InsertCommand, the UpdateCommand, and the DeleteCommand properties of the
OleDbDataAdapter object update the database with the data modifications that are run on a
DataSet object. The following source code demonstrate how to update a Dataset through
OleDbDataAdapter using a DataGridView. For running this source code , open a new VB.NET
project and drag two buttons and a DataGridView in the default form1 and copy and paste the
following Source Code.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1
Dim connetionString As String
Dim connection As OleDbConnection
Dim oledbAdapter As OleDbDataAdapter
Dim oledbCmdBuilder As OleDbCommandBuilder
Dim ds As New DataSet
Dim changes As DataSet
Dim i As Integer
Dim sql As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your
mdb filename;"
connection = New OleDbConnection(connetionString)
Sql = "select * from tblUsers"
Try
connection.Open()
oledbAdapter = New OleDbDataAdapter(Sql, connection)
oledbAdapter.Fill(ds)
DataGridView1.Data Source= ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try

End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Try
oledbCmdBuilder = New OleDbCommandBuilder(oledbAdapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
oledbAdapter.Update(ds.Tables(0))
End If
ds.AcceptChanges()
MsgBox("Save changes")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

How to create a DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used
to sort, filter, and search in a DataTable , additionally we can add new rows and modify the
content in a DataTable. DataViews can be created and configured both design time and run time .
Changes made to a DataView affect the underlying DataTable automatically, and changes made
to the underlying DataTable automatically affect any DataView objects that are viewing the
DataTable.
We can create DataView in two different ways. We can use the DataView constructor, or you can
create a reference to the DefaultView property of the DataTable. The DataView constructor can
be empty, or it can take either a DataTable as a single argument, or a DataTable along with filter
criteria, sort criteria, and a row state filter.
dataView = dataSet.Tables(0).DefaultView
The following source code shows how to create a DataView in VB.NET. Create a new VB.NET
project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the
following Source Code on button click event.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet

Dim dv As DataView
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Create DataView")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = ds.Tables(0).DefaultView
DataGridView1.DataSource = dv
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

How to sort DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used
to sort, filter, and search data in a DataTable , additionally we can add new rows and modify the
content in a DataTable. DataViews can be created and configured at both design time and run
time . Changes made to a DataView affect the underlying DataTable automatically, and changes
made to the underlying DataTable automatically affect any DataView objects that are viewing
that DataTable.
We can sort single or multiple fields in a DataView , also we can specify the sort order like ASC
(ascending) and DESC (descending) . The following example creates a View and apply sort on
the column Product_Price in descending order. Create a new VB.NET project and drag a
DataGridView and a Button on default Form Form1 , and copy and paste the following Source
Code on button click event.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet

Dim dv As DataView
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Sort DataView")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = New DataView(ds.Tables(0), "Product_Price > 100",
"Product_Price Desc", DataViewRowState.CurrentRows)
DataGridView1.DataSource = dv
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

How to Filter DataView


DataView enables you to create different views of the data stored in a DataTable. That is we can
customize the views of data from a DataTable. DataView can be used to sort, filter, and search a
DataTable , additionally we can add new rows and modify the content in a DataTable. We can
create DataView in two ways. Either we can use the DataView constructor, or we can create a
reference to the DefaultView property of the DataTable. Also we can create multiple DataViews
for any given DataTable.
The following source code creates a view that shows all Product Details where the Product Price
less than 500. Create a new VB.NET project and drag a DataGridView and a Button on default
Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim dv As DataView

Dim sql As String


connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Filter DataView")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = New DataView(ds.Tables(0), "Product_Price < = 500",
"Product_Name", DataViewRowState.CurrentRows)
DataGridView1.DataSource = dv
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

How to Find a row in DataView


The DataView provides different views of the data stored in a DataTable. The constructor for the
DataView class initializes a new instance of the DataView class and accepts the DataTable as an
argument. We can create DataView in two ways. Either we can use the DataView constructor, or
we can create a reference to the DefaultView property of the DataTable. We can create multiple
DataViews for any given DataTable.
We can search in a DataView according to the sort key values by using the Find method . The
Find method returns an integer with the index of the DataRowView that matches the search
criteria. If more than one row matches the search criteria, only the index of the first matching
DataRowView is returned. If no matches are found, Find returns -1
Dim index As Integer = DataView.Find("Product5")
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet

Dim dv As DataView
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
connection = New SqlConnection(connectionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Find Row DataView")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = New DataView(ds.Tables(0))
dv.Sort = "Product_Name"
Dim index As Integer = dv.Find("Product5")
If index = -1 Then
MsgBox("Item Not Found")
Else
MsgBox(dv(index)("Product_id").ToString() & "
("Product_Name").ToString())
End If

" & dv(index)

Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

How to add new rows in DataView


The DataView provides different views of the data stored in a DataTable. DataViews can be
created and configured at both design time and run time . We can create DataView in two ways.
Either we can use the DataView constructor, or we can create a reference to the DefaultView
property of the DataTable. We can create multiple DataViews for any given DataTable.
We can add new rows in the DataView using AddNew method in the DataView. The following
source code shows how to add new row in a DataView . Create a new VB.NET project and drag
a DataGridView and a Button on default Form Form1 , and copy and paste the following Source
Code on button click event.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim
Dim
Dim
Dim
Dim
Dim
Dim

connetionString As String
connection As SqlConnection
command As SqlCommand
adapter As New SqlDataAdapter
ds As New DataSet
dv As DataView
sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Add New")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = New DataView(ds.Tables(0))
Dim newRow As DataRowView = dv.AddNew()
newRow("Product_ID") = 7
newRow("Product_Name") = "Product 7"
newRow("Product_Price") = 111
newRow.EndEdit()
dv.Sort = "product_id"
DataGridView1.DataSource = dv
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

How to update rows in DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used
to sort, filter, and search a DataTable , additionally we can add new rows and modify the content
in a DataTable. We can create DataView in two ways. Either we can use the DataView
constructor, or we can create a reference to the DefaultView property of the DataTable. Also we
can create multiple DataViews for any given DataTable.
We can update the data in a DataView . The following source code shows how to update data in a
DataView . Create a new VB.NET project and drag a DataGridView and a Button on default
Form Form1 , and copy and paste the following Source Code on button click event.
Download Source Code
Print Source Code

Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim dv As DataView
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Update")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = New DataView(ds.Tables(0), "", "Product_Name",
DataViewRowState.CurrentRows)
Dim index As Integer = dv.Find("Product5")
If index = -1 Then
MsgBox("Product not found")
Else
dv(index)("Product_Name") = "Product11"
MsgBox("Product Updated !")
End If
DataGridView1.DataSource = dv
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

How to delete rows in DataView


The DataView provides different views of the data stored in a DataTable. DataView can be used
to sort, filter, and search data in a DataTable , additionally we can add new rows and modify the
content in a DataTable. Also we can delete the data from the DataView . The following source
code shows how to delete the data from DataView.
Download Source Code
Print Source Code

Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter
Dim ds As New DataSet
Dim dv As DataView
Dim sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Delete Row")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = New DataView(ds.Tables(0), "", "Product_ID",
DataViewRowState.CurrentRows)
dv.Table.Rows(3).Delete()
DataGridView1.DataSource = dv
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

How to create a new DataTable from DataView


The DataView provides different views of the data stored in a DataTable. That is we can
customize the views of data from a DataTable. Changes made to a DataView affect the
underlying DataTable automatically, and changes made to the underlying DataTable
automatically affect any DataView objects that are viewing that DataTable. We can create a new
DataTable from the DataView . We can use the ToTable method to copy all the rows and
columns, or a subset of the data into a new DataTable.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

Dim
Dim
Dim
Dim
Dim
Dim
Dim

connetionString As String
connection As SqlConnection
command As SqlCommand
adapter As New SqlDataAdapter
ds As New DataSet
dv As DataView
sql As String
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
sql = "Select * from product"
connection = New SqlConnection(connetionString)
Try
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds, "Copy to DataTable")
adapter.Dispose()
command.Dispose()
connection.Close()
dv = New DataView(ds.Tables(0), "Product_Price <= 200",
"Product_ID", DataViewRowState.CurrentRows)
Dim dTable As DataTable
dTable = dv.ToTable
DataGridView1.DataSource = dTable
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

.Net Remoting Architecture


The .NET Remoting provides an inter-process communication between Application Domains by
using Remoting Framework. The applications can be located on the same computer, different
computers on the same network, or on computers across separate networks. The .NET Remoting
supports distributed object communications over the TCP and HTTP channels by using Binary or
SOAP formatters of the data stream.
The main three components of a Remoting Framework are :
1. Remotable Object.
2. Remote Listener Application - (listening requests for Remote Object)
3. Remote Client Application - (makes requests for Remote Object)
The Remote Object is implemented in a class that derives from System.MarshalByRefObject .

You can see the basic workflow of .Net Remoting from the above figure. When a client calls the
Remote method, the client does not call the methods directly . It receives a proxy to the remote
object and is used to invoke the method on the Remote Object. Once the proxy receives the
method call from the Client , it encodes the message using appropriate formatter (Binary
Formatter or SOAP Formatter ) according to the Configuration file. After that it sends the call to
the Server by using selected Channel (TcpChannel ,HttpChannel). The Server side channel
receives the request from the proxy and forwards it to the Server on Remoting system, which
locates and invokes the methods on the Remote Object. When the execution of remote method is
complete, any results from the call are returned back to the client in the same way.
Before an object instance of a Remotable type can be accessed, it must be created and initialized
by a process known as Activation. Activation is categorized in two models , they are Clientactivated Objects and Server-activated Objects.
Remote Activation
The real difference between client-activated and server-activated objects is that a server-activated
object is not really created when a client instantiates it. Instead, it is created as needed.
By default the .NET Framework ships with two formatters(Binary Formatter or SOAP
Formatter ) and two channels(TcpChannel ,HttpChannel).
Remote Channels
Remote Formatters
Formatters and Channel are configured by using Configuration files. It can be easily Configured
by using XML-based files.
Remote Configuration

The .NET Remoting is easy to use and powerful, largely because it is based on the Common
Type System (CTS) and the Common Language Runtime (CLR). From the following link , you
can understand .Net Remoting components in detail.

VB.NET Remoting Apllication


The .NET Remoting supports Distributed Object communications over the TCP and HTTP
transports by using Binary or SOAP representation of the data stream. For building a Remoting
application in VB.NET ,you must have an implementation of a Remotable type, a Listening or
Host Application domain, a Client or calling application domain, and you must Configure the
remoting system in each application domain to use remote activation for the remotable type.
Remotable Object
Remote Listener Application
Remote Client Application
Remote Configuration

Remotable Type
Any object outside the application domain of the caller application should be considered as
Remote Object. A Remote Object that should be derived from MarshalByRefObject Class. Any
object can be changed into a Remote Object by deriving it from MarshalByRefObject . Objects
without inheriting from MarshalByRefObject are called Non-remotable Objects.
The following example creating a Remote Object in VB.Net, RemoteTime , which send the
current time to the Client Application using Remoting Framework. The RemoteTime class is
derived from MarshalByRefObject and inside the class it has a method getTime() which return
the current time from Remote Object.
Download Source Code
Print Source Code
Imports System
Public Class RemoteTime
Inherits MarshalByRefObject
Private currentTime As String = ""
Public Function getTime() As String
currentTime = DateTime.Now.ToShortTimeString()
Return "Remote Server Time : " & currentTime
End Function
End Class

Copy and paste the above VB.Net source code into a file and save it as RemoteTime.vb
Compile the class RemoteTime.vb into a library using the command-line tools that ship with
the
.NET
Framework
SDK.
At the command prompt in the directory in which you saved the file, type the following
command:
vbc

/t:library

RemoteTime.vb

After you compile the RemoteTime.vb , you will get a file called RemoteTime.dll in the
directory which you saved the source file.

Remote Listener Application


We already created a Remote Type Object RemoteTime in the previous section. We have to
create a listener Object for enable Objects in other application domains to create instances of this
object (RemoteTime) Remotely. When creating a listener Object we have to choose and register
a channel for handle the networking protocol and serialization formats and register the Type with
the .NET Remoting system, so that it can use the channel to listen for requests for the Type.
Channels are Objects that responsible of handling the network protocols and serialization
formats.
In the following example we are creating a listener application TimeListener . It will act as a
listener Object for the Remote Type RemoteTime. The Listener class TimeListener must be able
to find the TimeListener.exe.config file to load the configuration for the RemotableType class.
Download Source Code
Print Source Code
Imports System
Imports System.Runtime.Remoting
Public Class TimeListener
Public Shared Sub Main()
RemotingConfiguration.Configure("TimeListener.exe.config")
Console.WriteLine("Listening for requests from the Client. Press Enter
to exit...")
Console.ReadLine()
End Sub
End Class

Copy and paste the above VB.Net source code into a file and save it as TimeListener.vb.
We have to create additional configuration file to provide the communication information to the
listener Object. The configuration file is an XML structured file. We can specify the Activation
Mode , the Remote Type , Channel , port for communication etc. through the configuration file .

Click

here

to

download

TimeListener.exe.config

Compile the class file TimeListener.vb using the command-line tools that ship with the .NET
Framework
SDK.
At the command prompt in the directory in which you saved the file, type the following
command:
vbc

/r:RemoteTime.dll

TimeListener.vb

After you compile the TimeListener.vb , you will get a file called TimeListener.exe in the
directory which you saved the source file

Remote Client Application


The Client application for calling Remote Object's method in VB.Net is pretty simple and
straight forward. The .NET Remoting system will intercept the client calls, forward them to the
remote object, and return the results to the client. The Client Application have to register for the
Remote Type also.
Here in the Client application in VB.Net , creating an instance of the Remote Type, RemoteTime
Object , and call the method getTime() . Aditionally it uses the configuration file
Client.exe.config for the communication information for the Remoting Framework.
Download Source Code
Print Source Code
Imports System
Imports System.Runtime.Remoting
Public Class Client
Public Shared Sub Main()
RemotingConfiguration.Configure("Client.exe.config")

Dim remoteTimeObject As New RemoteTime()


Console.WriteLine(remoteTimeObject.getTime())
End Sub
End Class

Copy and paste the above VB.Net source code into a file and save it as Client.vb.
We have to create additional configuration file to provide the communication information to the
Client Object. The configuration file is a an XML structured file. We can specify the Remote
Type , Channel , port for communication etc. through the configuration file .

Click

here

to

download

Client.exe.config

Compile the class file Client.vb using the command-line tools that ship with the .NET
Framework
SDK.
At the command prompt in the directory in which you saved the file, type the following
command:
vbc

/r:RemoteTime.dll

Client.vb

After you compile the Client.vb , you will get a file called Client.exe in the directory which you
saved the source file

Compiling and Running Remote Application


The .NET Remoting is one of several ways to establish communication between application
domains using the .NET Framework.
The main three components of a Remoting Framework are a Remotable Object , Listener
Application for listening requests for remote object and a Client Application makes requests for
remote object. Additionally you need Configuration files for your Listener Application and
Client Application.
Compiling the VB.Net source code files

Create a new folder SRC and put the three VB.Net source code files in that folder.
1. RemoteTime.vb
2. TimeListener.vb
3. Client.vb
Add the two configuration files in the same folder.
1. TimeListener.exe.config
2. Client.exe.config
Compile these VB.Net class files using the command-line tools that ship with the .NET
Framework SDK.
vbc /t:library RemoteTime.vb
vbc /r:RemoteTime.dll TimeListener.vb
vbc /r:RemoteTime.dll Client.vb
Note: You have to provide the physical path of each source files when you compile the source
code , for example : if the source code files are in the folder c:\SRC , you have to give path like
vbc /r:c:\SRC\RemoteTime.dll c:\SRC\TimeListener.vb
After you complied the VB.Net source code files, you will get additional three files in the SRC
folder. They are :
RemoteTime.dll
TimeListener.exe
Client.exe
To run the application
Create two new folders and give the name like Server and Client respectively.
Copy RemoteTime.dll , TimeListener.exe and TimeListener.exe.config to the Server folder.
Copy RemoteTime.dll , Client.exe and Client.exe.config to the Client folder.
Open a command prompt on Server folder and type TimeListener

Then you will get a screen showing "Listening for requests from the Client. Press Enter to exit..."
Open a command prompt on Client folder and type Client.
Then you will get the current time from remote Object.
Now you have done your first .Net Remoting VB.Net project successfully . Try to explore more
on Remoting ...

Remoting Configurations
Configuration provides the necessary information to .Net Remoting Framework . We can provide
.Net Remoting configuration parameters in two ways. Either we can provide the information to
the Server and the Client directly by program coding or through a Machine.config file. Using
configuration file give better advantage over coding because the parameters of remote object can
be configured without changing any program coding and avoid recompile the source code.
Following are the information provided by configuration file :
Metadata describing the Remote Type
Type of Activation
Channels
The URL that uniquely identifies the object of that type.
We have to provide configuration information to Listener Object and also Client Object .
Listener Configuration

Click here to download TimeListener.exe.config .


Client Configuration

Click here to download Client.exe.config .

Remoting Activation
The .Net Remoting framework supports Server and Client activation of Remote Objects. Before
an Object instance of a Remotable type can be accessed, it must be created and initialized by
Activation process. There are commonly two types of activation modes : Server Activation and
Client Activation mode. Server activation is normally used when a Remote objects is not
required to maintain any state between method calls. Client Activated objects are instantiated
from the client, and the client manages the lifetime of the Remote Object by using a lease-based
system provided for that purpose.
SingleCall Objects and Singleton Objects belong to Server Activation mode. For SingleCall
objects the server will create a single object, execute the method, and destroy the object again.
On the other hand with Singleton mode only one object is created at all. Singleton objects can be
used to share information between multiple clients. The real distinction between Client Activated
and Server Activated object is that a server-activated object is not really created when a client
instantiates it. Instead, it is created as needed.

Remoting Channel
In .Net Remoting Channels are used to transport messages to and from the Remote Objects.
Channels are Objects that responsible of handling the network protocols and serialization
formats. In .Net Remoting channel can be implement either by calling the method
ChannelServices.RegisterChannel or by using configuration file. Channels should be registered
before objects are registered.
When a channel is registered, it automatically starts listening for client requests at the specified
port. At least one channel must be registered with the remoting framework before a Remote
object can be called. There are two types of Channels available in .Net Remote Framework:
HTTP channel and TCP channel. The HTTP channel transports messages to and from remote
objects using the SOAP protocol. The TCP channel uses a binary formatter to serialize all
messages to a binary stream and transport the stream to the target URI using the TCP protocol.

Remoting Channel
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 SOAP Formatter System.Runtime.Serialization.Formatters.Soap . The data in binary Formatter
has smaller size when compared to SOAP Formatter. The SOAP Formatter is an XML
based cross platform text format , so it can be human readable. The data in a SOAP
Formatter larger size compared to Binary Formatter , so it can therefore reduce
overall performance.

How to XML in VB.NET


XML is a general purpose tag based language and very easy to transfer and store data across
applications. Like HTML , XML is a subset of SGML - Standard Generalized Markup Language.
XML is a platform independent language, so the information formatted in XML can be used in
any other platforms (Operating Systems). XML is a self describing language and it gives the data
as well as the rules to identify what information it contains.
XML files are made up of tags that contains data. Generally a start tag and end tag to hold the
data. For example, if you want to create an XML tag name "Header" , the start tag is like <
Header > and the end tag is like < /Header > . We can fill our information between these tags.
< Header > Header Content Here < /Header >
While creating an XML file , some important points have to remember :
* XML is case sensitive
ex: < Header > is not same as < HeadeR > .
* Tags must be closed in the reverse order that they were opened
ex : < first-tag >< second-tag > Data here < /second-tag > < /first-tag >
Sample XML File

The .Net technology is widely supported XML file format. The .Net Framework provides the
Classes for read, write, and other operations in XML formatted files . These classes are stored in
the namespaces like System.Xml, System.Xml.Schema, System.Xml.Serialization,
System.Xml.XPath, System.Xml.Xsl etc. The Dataset in ADO.NET uses XML as its internal
storage format.
You can use any text editor to create an XML file . More over XML files are readable by humans
as well as computers. From the following links you can see how to use XML in VB.NET.

How to create an XML file in VB.NET


XML is a platform independent language, so the information formatted in XML can be used in
any other platforms (Operating Systems). If we create an XML file in one platform it can be used
in other platforms also.
For creating a new XML file in VB.NET, we are using XmlTextWriter class . The class takes
FileName and Encoding as argument. Also we are here passing formating details . The following
source code creating an XML file product.xml and add four rows in the file.
Download Source Code
Print Source Code
Imports System.Xml
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim writer As New XmlTextWriter("product.xml",
System.Text.Encoding.UTF8)
writer.WriteStartDocument(True)
writer.Formatting = Formatting.Indented

writer.Indentation = 2
writer.WriteStartElement("Table")
createNode(1, "Product 1", "1000", writer)
createNode(2, "Product 2", "2000", writer)
createNode(3, "Product 3", "3000", writer)
createNode(4, "Product 4", "4000", writer)
writer.WriteEndElement()
writer.WriteEndDocument()
writer.Close()
End Sub
Private Sub createNode(ByVal pID As String, ByVal pName As String, ByVal
pPrice As String, ByVal writer As XmlTextWriter)
writer.WriteStartElement("Product")
writer.WriteStartElement("Product_id")
writer.WriteString(pID)
writer.WriteEndElement()
writer.WriteStartElement("Product_name")
writer.WriteString(pName)
writer.WriteEndElement()
writer.WriteStartElement("Product_price")
writer.WriteString(pPrice)
writer.WriteEndElement()
writer.WriteEndElement()
End Sub
End Class

Output of the above source code :

How to open and read an XML file in VB.NET


XML is a self describing language and it gives the data as well as the rules to extract what the
data it contains. Reading an XML file means that we are reading the information embedded in
XML tags in an XML file.

In the previous program we create an XML file and named it as products.xml. The following
program read that file and extract the contents inside the XML tag. We can read an XML file in
several ways depends on our requirement. This program read the content in Node wise . Here we
are using XmlDataDocument class to read the XML file . In this program it search the Node <
Product > and its child Nodes and extract the data in child nodes.
Download Source Code
Print Source Code
Imports System.Xml
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim xmldoc As New XmlDataDocument()
Dim xmlnode As XmlNodeList
Dim i As Integer
Dim str As String
Dim fs As New FileStream("products.xml", FileMode.Open,
FileAccess.Read)
xmldoc.Load(fs)
xmlnode = xmldoc.GetElementsByTagName("Product")
For i = 0 To xmlnode.Count - 1
xmlnode(i).ChildNodes.Item(0).InnerText.Trim()
str = xmlnode(i).ChildNodes.Item(0).InnerText.Trim() & " | " &
xmlnode(i).ChildNodes.Item(1).InnerText.Trim() & " | " &
xmlnode(i).ChildNodes.Item(2).InnerText.Trim()
MsgBox(str)
Next
End Sub
End Class

Click here to download the input file product.xml

How to create an XML file in VB.NET using Dataset


XML is a tag based language, that means the document is made up of XML tags that contain
information. We can create an XML file in several ways.
In the previous section we create an XML file using XmlTextWriter Class. Here we are creating
an XML file Product.XML using an ADO.NET Dataset. For that we have to manually create a
Datatable first and add the data of Product.XML in the Datatable . Then add the Datatable in a
Dataset . Call the method WriteXml of Dataset and pass the file name Product.XML as argument.
Download Source Code
Print Source Code
Imports System.Xml
Imports System.Data

Public Class Form1


Dim dt As DataTable
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim ds As New DataSet
dt = New DataTable()
dt.Columns.Add(New DataColumn("Product_ID",
Type.GetType("System.Int32")))
dt.Columns.Add(New DataColumn("Product_Name",
Type.GetType("System.String")))
dt.Columns.Add(New DataColumn("product_Price",
Type.GetType("System.Int32")))
fillRows(1, "product1", 1111)
fillRows(2, "product2", 2222)
fillRows(3, "product3", 3333)
fillRows(4, "product4", 4444)
ds.Tables.Add(dt)
ds.Tables(0).TableName = "product"
ds.WriteXml("Product.xml")
MsgBox("Done")
End Sub
Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal
pPrice As Integer)
Dim dr As DataRow
dr = dt.NewRow()
dr("Product_ID") = pID
dr("Product_Name") = pName
dr("product_Price") = pPrice
dt.Rows.Add(dr)
End Sub
End Class

How to read an XML file in VB.NET using ADO.NET Dataset


XML is a platform independent language, so the information formatted in XML can be use in
any other platforms (Operating Systems) . The .Net technology is widely supported XML file
format. The .Net Framework provides the Classes for read, write, and other operations in XML
formatted files .
In the previous section we already saw how to read an XML file through Node navigation . Here
we are going to read an XML file using an DataSet. Here Dataset is using an XmlReader for read
the content of the file. Locate the XML file using XmlReader and pass the XmlReader as
argument of Dataset.
Click here to download the input file product.xml
Download Source Code

Print Source Code


Imports System.Xml
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim xmlFile As XmlReader
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
Dim ds As New DataSet
ds.ReadXml(xmlFile)
Dim i As Integer
For i = 0 To ds.Tables(0).Rows.Count - 1
MsgBox(ds.Tables(0).Rows(i).Item(1))
Next
End Sub
End Class

How to create an XML file from SQL in VB.NET


XML is a general purpose tag based language and very easy to transfer and store data across
applications. The .Net technology is widely supported XML file format. The .Net Framework
provides the Classes for read, write, and other operations in XML formatted files . Moreover the
Dataset in ADO.NET uses XML format as its internal storage format.
There are several ways to create an XML file . In the previous sections we already saw how to
create an XML file using XmlTextWriter and also created an XML file using manually created
Dataset. Here we are going to create an XML file from Database. Make an SQL connection to
the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml() method
and pass the file name as argument.
Download Source Code
Print Source Code
Imports System.Xml
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim ds As New DataSet
Dim sql As String
connetionString = "Data Source=servername;Initial
Catalog=databsename;User ID=username;Password=password"
connection = New SqlConnection(connetionString)
sql = "select * from Product"
Try
connection.Open()

adapter = New SqlDataAdapter(sql, connection)


adapter.Fill(ds)
connection.Close()
ds.WriteXml("Product.xml")
MsgBox("Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

You have to pass necessary database connection information to connection string.

How to search in an XML file


XML files are made up of tags that contains information. The .Net technology is widely
supported XML file format. Also the Dataset in ADO.NET uses XML format as its internal
storage format.
The following source code shows how to search an item in an XML file using Dataset . Here
Dataset using an XmlReader for read the content of the file. Locate the XML file using
XmlReader and pass the XmlReader as argument of Dataset. By using the Dataset , search the
product Product2 in the file Product.XML with the help of DataView.
Download Source Code
Print Source Code
Imports System.Xml
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim xmlFile As XmlReader
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
Dim ds As New DataSet
Dim dv As DataView
ds.ReadXml(xmlFile)
dv = New DataView(ds.Tables(0))
dv.Sort = "Product_Name"
Dim index As Integer = dv.Find("Product2")
If index = -1 Then
MsgBox("Item Not Found")
Else
MsgBox(dv(index)("Product_Name").ToString() & "
("Product_Price").ToString())
End If
End Sub

Click here to download the input file product.xml

" & dv(index)

How to filter data in an XML file


XML is a platform independent language, so the information formatted in XML can be used in
any other platforms (Operating Systems). If we create an XML file in one platform it can be used
in other platforms also. The .Net technology is widely supported XML file format. Also the
Dataset in ADO.NET uses XML format as its internal storage format.
Here we are going to filter an XML file content and store the result in a newly created XML file.
We have an XML file Product.XML , and it has a field Product_Price. We are giving a search
criteria like the Product_Price >= 3000 and store the result in a newly created XML file
Result.XML.
Download Source Code
Print Source Code
Imports System.Xml
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim xmlFile As XmlReader
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
Dim ds As New DataSet
Dim dv As DataView
ds.ReadXml(xmlFile)
dv = New DataView(ds.Tables(0), "Product_price > = 3000",
"Product_Name", DataViewRowState.CurrentRows)
dv.ToTable().WriteXml("Result.xml")
MsgBox("Done")
End Sub
End Class

Click here to download the input file product.xml

How to insert data from xml to database


XML is a general purpose tag based language and very easy to transfer and store data across
applications. The .Net technology is widely supported XML file format. The .Net Framework
provides the Classes for read, write, and other operations in XML formatted files . Moreover the
Dataset in ADO.NET uses XML format as its internal storage format.
Here we are going to insert the values of an XML file to a Database Table using SQL insert
command. Here the Dataset using an XmlReader for read the content of the XML file Product.XML . Locate the XML file using XmlReader and pass the XmlReader as argument of
Dataset. Also establish a connection to the Database using a connectionstring . After getting the
data from XML file to the Dataset , we can loop through the dataset values and use insert
command to add the values to the Product table in the Databse.

Download Source Code


Print Source Code
Imports System.Xml
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adpter As New SqlDataAdapter
Dim ds As New DataSet
Dim xmlFile As XmlReader
Dim sql As String
Dim product_ID As Integer
Dim Product_Name As String
Dim product_Price As Double
connetionString = "Data Source=servername;Initial
Catalog=databsename;User ID=username;Password=password"
connection = New SqlConnection(connetionString)
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
ds.ReadXml(xmlFile)
Dim i As Integer
connection.Open()
For i = 0 To ds.Tables(0).Rows.Count - 1
product_ID = Convert.ToInt32(ds.Tables(0).Rows(i).Item(0))
Product_Name = ds.Tables(0).Rows(i).Item(1)
product_Price = Convert.ToDouble(ds.Tables(0).Rows(i).Item(2))
sql = "insert into Product values(" & product_ID & ",'" &
Product_Name & "'," & product_Price & ")"
command = New SqlCommand(sql, connection)
adpter.InsertCommand = command
adpter.InsertCommand.ExecuteNonQuery()
Next
connection.Close()
End Sub
End Class

You have to pass necessary database connection information to connection string.


Click here to download the input file product.xml

How to create an Excel file from XML


XML is a platform independent language, so the information formatted in XML can be used in
any other platforms (Operating Systems). XML is a self describing language and it gives the data
as well as the rules to identify what the data it contains.

Here we are going to read from an XML file content and write the same content to an Excel file.
Using an XmlReader for read the XML file to the Dataset . Loop through the Dataset and add the
content to the Excel file . For create an excel file you have to add reference of Excel library to
you project .
Download Source Code
Print Source Code
Imports System.Xml
Imports System.Data
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim ds As New DataSet
Dim xmlFile As XmlReader
Dim i, j As Integer
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
ds.ReadXml(xmlFile)
For i = 0 To ds.Tables(0).Rows.Count - 1
For j = 0 To ds.Tables(0).Columns.Count - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
ds.Tables(0).Rows(i).Item(j)
Next
Next
xlWorkSheet.SaveAs("xml2excel.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try

End Sub
End Class

Click here to download the input file product.xml

How to create an XML file from Excel


XML is a general purpose tag based language and very easy to transfer and store data across
applications. The .Net Framework provides the Classes for read, write, and other operations in
XML formatted files .
The following program shows how to create an XML file from an Excel file content . Here we
are using an OleDbConnection to read the excel file and store the content to a Dataset . Call the
method WriteXml of Datset to write to the XML file.
Download Source Code
Print Source Code
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim ds As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection _
("provider=Microsoft.Jet.OLEDB.4.0;Data
Source='xl2xml.xls';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter _
("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "Product")
ds = New System.Data.DataSet
MyCommand.Fill(ds)
MyConnection.Close()
ds.WriteXml("Product.xml")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class

Click here to download the input excel file xl2xml.xls

How to xml to DataGridView


XML is a platform independent language, so the information formatted in XML file can be use in
any other platforms . The .Net technology is widely supported XML file format. The following

source code shows , how to load data in a DataGridView from an XML file . Here the Dataset
using an XmlReader for read the content of the XML file - Product.XML . Locate the XML file
using XmlReader and pass the XmlReader as argument of Dataset. When the Dataset retrieves
the data, it passes as DataSource to DataGridView .
Download Source Code
Print Source Code
Imports System.Xml
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim xmlFile As XmlReader
xmlFile = XmlReader.Create("Product.xml", New XmlReaderSettings())
Dim ds As New DataSet
ds.ReadXml(xmlFile)
DataGridView1.DataSource = ds.Tables(0)
End Sub
End Class

Click here to download the input file product.xml

How to create a TreevView from XML


XML is a self describing language and it gives the data as well as the rules to extract what the
data it contains. Reading an XML file means that we are reading the data embedded in tags in an
XML file.

In the previous example we already saw how to read an XML file Node wise. Here we are
reading XML file as Node and pass the Nodes data to TreeView.
Download Source Code
Print Source Code
Imports System.Xml
Imports System.io
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim xmldoc As New XmlDataDocument()
Dim xmlnode As XmlNode
Dim fs As New FileStream("tree.xml", FileMode.Open, FileAccess.Read)
xmldoc.Load(fs)
xmlnode = xmldoc.ChildNodes(1)
TreeView1.Nodes.Clear()
TreeView1.Nodes.Add(New TreeNode(xmldoc.DocumentElement.Name))
Dim tNode As TreeNode
tNode = TreeView1.Nodes(0)
AddNode(xmlnode, tNode)
End Sub
Private Sub AddNode(ByVal inXmlNode As XmlNode, ByVal inTreeNode As
TreeNode)
Dim xNode As XmlNode
Dim tNode As TreeNode
Dim nodeList As XmlNodeList
Dim i As Integer
If inXmlNode.HasChildNodes Then
nodeList = inXmlNode.ChildNodes
For i = 0 To nodeList.Count - 1
xNode = inXmlNode.ChildNodes(i)
inTreeNode.Nodes.Add(New TreeNode(xNode.Name))
tNode = inTreeNode.Nodes(i)
AddNode(xNode, tNode)
Next
Else
inTreeNode.Text = inXmlNode.InnerText.ToString
End If
End Sub
End Class

Click here to download the input file tree.xml

How to create Crystal Reports from XML


XML is a self describing language and it gives the data as well as the rules to identify what the
data it contains. The .Net Framework provides the Classes for read, write, and other operations in
XML formatted files . We can use XML as a Data Source to Crystal Reports like a Database .

Click here to see, How to create Crystal Reports from xml .

How to serialization in xml


XML Serialization is the process of serializing a .Net Object to the form of XML or from an
XML to .Net Object. The primary purpose of XML serialization in the .NET Framework is to
enable the conversion of XML documents and streams to common language runtime objects and
vice versa. This is the process of converting an object into a form that can be readily transported.
During XML serialization, only the public properties and fields of an object are serialized. The
following links gives you more details about XML Serialization and De-serialization.
How to serialize a .Net Object to XML
How to de-serialize XML to .Net Object

How to serialize a .Net Object to XML


Serialization of XML to common language runtime objects enables one to convert XML
documents into a form where they are easier to process using conventional programming
languages. The .Net technology is widely supported XML file format. The .Net Framework
provides the Classes for read, write, and other operations in XML formatted files .
The following program shows how to serialize a Dataset to an XML disk file . Here we are using
XmlSerializer class for serialize the Dataset Object.
Download Source Code
Print Source Code
Public Class Form1
Dim dt As DataTable
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim ds As New DataSet
dt = New DataTable()
dt.Columns.Add(New DataColumn("Product_ID",
Type.GetType("System.Int32")))
dt.Columns.Add(New DataColumn("Product_Name",
Type.GetType("System.String")))
dt.Columns.Add(New DataColumn("product_Price",
Type.GetType("System.Int32")))
fillRows(1, "product1", 9999)
fillRows(2, "product2", 2222)
fillRows(3, "product3", 3333)
fillRows(4, "product4", 4444)
ds.Tables.Add(dt)
ds.Tables(0).TableName = "product"
Dim serialWriter As StreamWriter

serialWriter = New StreamWriter("serialXML.xml")


Dim xmlWriter As New XmlSerializer(ds.GetType())
xmlWriter.Serialize(serialWriter, ds)
serialWriter.Close()
ds.Clear()
End Sub
Private Sub fillRows(ByVal pID As Integer, ByVal pName As String, ByVal
pPrice As Integer)
Dim dr As DataRow
dr = dt.NewRow()
dr("Product_ID") = pID
dr("Product_Name") = pName
dr("product_Price") = pPrice
dt.Rows.Add(dr)
End Sub
End Class

Click here to download serialXML.xml

How to de-serialize from an XML file to .Net Object


XML is a general purpose tag based language and very easy to transfer and store data across
applications. XML Serialization is the process of serializing a .Net Object to the form of XML
file or from an XML to .Net Object.
During XML serialization, only the public properties and fields of an object are serialized. The
following source code shows how to de-serialize the DataSet as it is streamed from an XML file
back into memory.
Download Source Code
Print Source Code
Imports System.Xml.Serialization
Imports System.io
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim ds As New DataSet
Dim xmlSerializer As XmlSerializer = New XmlSerializer(ds.GetType)
Dim readStream As FileStream = New FileStream("serialXML.xml",
FileMode.Open)
ds = CType(xmlSerializer.Deserialize(readStream), DataSet)
readStream.Close()
DataGridView1.DataSource = ds.Tables(0)
End Sub
End Class

VB.NET DataGridView binding - Sql Server


You can extend the DataGridView control in a number of ways to build custom behaviors into
your applications. The DataGridView 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. One very common use of the DataGridView control is binding to a table in a database.
Unbound 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 SQL Server dataset in a DataGridView.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=.;Initial
Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Authors"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
End Sub
End Class

DataGridView binding - OLEDB in VB.NET


The DataGridView can display data in Bound mode and unbound mode and Virtual mode. The
easiest way to get started using the DataGridView control is to use it in basic data binding
scenarios. The DataGridView control can display rows of data from a data source. When you
specify a data source for the DataGridView, 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 OLEDB dataset in a DataGridView.
Download Source Code
Print Source Code
Imports System.Data.OleDb
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
Dim connectionString As String =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="Your .mdb path";"
Dim sql As String = "SELECT * FROM Authors"
Dim connection As New OleDbConnection(connectionString)
Dim dataadapter As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
End Sub
End Class

DataGridView Sorting/Filtering in VB.NET


The DataGridView control provides a customizable table for displaying data. You can extend the
DataGridView control in a number of ways to build custom behaviors into your applications. A
DataView provides a means to filter and sort data within a DataTable. The following vb.net
program shows how to filter and sort a DataGridView by using a DataView Object.
Dim dv As DataView
dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc", DataViewRowState.CurrentRows)
DataGridView1.DataSource = dv
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=.;Initial
Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Titles"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Titles_table")
connection.Close()
Dim dv As DataView
dv = New DataView(ds.Tables(0), "Price > 19", "Price Desc",
DataViewRowState.CurrentRows)
DataGridView1.DataSource = dv
End Sub

End Class

DataGridView adding rows and columns in VB.NET


The DataGridView control is designed to be a complete solution for displaying tabular data with
Windows Forms. The DataGridView control is highly configurable and extensible, and it
provides many properties, methods, and events to customize its appearance and behavior. The
DataGridView control is used to display data from a variety of external data sources.
Alternatively, 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 Columns and Rows in a
DataGridView.
DataGridView1.Columns(Index).Name = "Column Name"
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name"
DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)
End Sub
End Class

DataGridView hiding rows and columns in VB.NET


The DataGridView control provides a customizable table for displaying data. It gives you
number of properties, methods and events to customize its appearance and behavior. Displaying
data in a tabular format is a task you are likely to perform frequently. The DataGridView control
is designed to be a complete solution for displaying tabular data with Windows Forms . The
following vb.net source code manually creates a DataGridView columns and rows and hide the
second column and second row.

DataGridView1.Rows(Index).Visible = False
DataGridView1.Columns(Index).Visible = False
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name"
DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)
DataGridView1.Rows(1).Visible = False
End Sub
End Class

DataGridView ReadOnly rows and columns in


VB.NET
The DataGridView control can display rows of data from a data source. You can extend the
DataGridView control in a number of ways to build custom behaviors into your applications. The
ReadOnly property indicates whether the data displayed by the cell can be edited or not. You can
set ReadOnly Property in three levels. You can make entire dataGridView as ReadOnly.
dataGridView1.ReadOnly = true
You can make entire row as ReadOnly
dataGridView1.Rows(index).ReadOnly = true;
You can make entire Column as ReadOnly
dataGridView1.Columns(index).ReadOnly = true;

The following vb.net source code shows how to make a row as Readonly in a DataGridView.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name"
DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)
DataGridView1.Rows(1).ReadOnly = True
End Sub
End Class

Adding Button to DataGridView in VB.NET


The DataGridView control is highly configurable and extensible, and it provides many
properties, methods, and events to customize its appearance and behavior. The DataGridView
control provides TextBox, CheckBox, Image, Button, ComboBox and Link columns with the
corresponding cell types. With the DataGridViewButtonColumn, you can display a column of
cells that contain buttons.You can respond to user clicks in button cells by handling the
DataGridView.CellClick event.
The following vb.net program shows how to add a Button in Cell of a DataGridView control.
Also it showing in the DataGridView.CellClick event which button the user clicked.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name"

DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)
Dim btn As New DataGridViewButtonColumn()
DataGridView1.Columns.Add(btn)
btn.HeaderText = "Click Data"
btn.Text = "Click Here"
btn.Name = "btn"
btn.UseColumnTextForButtonValue = True
End Sub
Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e
As System.Windows.Forms.DataGridViewCellEventArgs) Handles
DataGridView1.CellClick
If e.ColumnIndex = 3 Then
MsgBox(("Row : " + e.RowIndex.ToString & " Col : ") +
e.ColumnIndex.ToString)
End If
End Sub
End Class

Adding CheckBox to DataGridView in VB.NET


The DataGridView control uses several column types to display its information and enable users
to modify or add information. The DataGridView control provides TextBox, CheckBox, Image,
Button, ComboBox and Link columns with the corresponding cell types.
The following vb.net program shows how to add a CheckBox in Cell of a DataGridView control
and set the third row checkbox value as true. If you want to respond immediately when users
click a check box cell, you can handle the CellClick event, but this event occurs before the cell
value is updated.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"

DataGridView1.Columns(1).Name = "Product Name"


DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)
Dim chk As New DataGridViewCheckBoxColumn()
DataGridView1.Columns.Add(chk)
chk.HeaderText = "Check Data"
chk.Name = "chk"
DataGridView1.Rows(2).Cells(3).Value = True
End Sub
End Class

Adding ComboBox to DataGridView in VB.NET


The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link
columns with the corresponding cell types. You can populate the drop down list used for all cells
the same way you would populate a ComboBox drop down list, either manually through the
collection returned by the Items property, or by binding it to a data source through the
DataSource, DisplayMember, and ValueMember properties.
The following vb.net program shows how to add a ComboBox in Cell of a DataGridView
control.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name"
DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)

Dim cmb As New DataGridViewComboBoxColumn()


cmb.HeaderText = "Select Data"
cmb.Name = "cmb"
cmb.MaxDropDownItems = 4
cmb.Items.Add("True")
cmb.Items.Add("False")
DataGridView1.Columns.Add(cmb)
End Sub
End Class

Adding Image to DataGridView in VB.NET


The DataGridView control and its related classes are designed to be a flexible, extensible system
for displaying and editing tabular data. We can add an Image control in a column of
DataGridView. This column type exposes Image and ImageLayout properties in addition to the
usual base class properties. Setting the columns Image property results in that image being
displayed by default for all the cells in that column. Populating an image column manually is
useful when you want to provide the functionality of a DataGridViewButtonColumn, but with a
customized appearance.
The following vb.net program shows how to add a Image in column of a DataGridView control.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name"
DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)
Dim img As New DataGridViewImageColumn()
Dim inImg As Image = Image.FromFile("Image Path")
img.Image = inImg
DataGridView1.Columns.Add(img)
img.HeaderText = "Image"

img.Name = "img"
End Sub
End Class

Adding ViewLink to DataGridView in VB.NET


The DataGridView control provides TextBox, CheckBox, Image, Button, ComboBox and Link
columns with the corresponding cell types. We can add hyperlink in the column of a
DataGridView , the column type contains cells of type DataGridViewLinkCell and renders the
text in the cell to look like a hyperlink. Link columns are not generated automatically when data
binding a DataGridView control. To use link columns, you must create them manually and add
them to the collection returned by the Columns property.
The following vb.net program shows how to add a hyperlink in a column of DataGridView
control.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
DataGridView1.ColumnCount = 3
DataGridView1.Columns(0).Name = "Product ID"
DataGridView1.Columns(1).Name = "Product Name"
DataGridView1.Columns(2).Name = "Product_Price"
Dim row As String() = New String() {"1", "Product 1", "1000"}
DataGridView1.Rows.Add(row)
row = New String() {"2", "Product 2", "2000"}
DataGridView1.Rows.Add(row)
row = New String() {"3", "Product 3", "3000"}
DataGridView1.Rows.Add(row)
row = New String() {"4", "Product 4", "4000"}
DataGridView1.Rows.Add(row)
Dim lnk As New DataGridViewLinkColumn()
DataGridView1.Columns.Add(lnk)
lnk.HeaderText = "Link Data"
lnk.Name = "http://vb.net-informations.com"
lnk.Text = "http://vb.net-informations.com"
lnk.UseColumnTextForLinkValue = True
End Sub
End Class

How to Paging in DataGridView

The DataGridView class allows customization of cells, rows, columns, and borders through the
use of its properties . If a DataGridView has lot of rows then we can implement paging
functionalities to the DataGridView control. While we implement paging we should know the
boundaries of the pages to enable the paging in the DatagridView.
The following vb.net program provides a way to programmatically implement paging in a
Windows Datagrid View control. Here the DataGridView rows fixed as five rows and other two
buttons are there for implementing paging functionalities.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Dim pagingAdapter As SqlDataAdapter
Dim pagingDS As DataSet
Dim scrollVal As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=.;Initial
Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM authors"
Dim connection As New SqlConnection(connectionString)
pagingAdapter = New SqlDataAdapter(sql, connection)
pagingDS = New DataSet()
connection.Open()

pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table")


connection.Close()
DataGridView1.DataSource = pagingDS
DataGridView1.DataMember = "authors_table"
End Sub
Private Sub button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles button2.Click
scrollVal = scrollVal - 5
If scrollVal <= 0 Then
scrollVal = 0
End If
pagingDS.Clear()
pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table")
End Sub
Private Sub button3_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles button3.Click
scrollVal = scrollVal + 5
If scrollVal > 23 Then
scrollVal = 18
End If
pagingDS.Clear()
pagingAdapter.Fill(pagingDS, scrollVal, 5, "authors_table")
End Sub
End Class

How to Formatting in DataGridView

The DataGridView control is highly configurable and extensible, and it provides many
properties, methods, and events to customize its appearance and behavior. You can extend the
DataGridView control in a number of ways to build custom behaviors into your applications.
The DataGridView control makes 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. You 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
DataGridViewCellStyle objects accessed through various DataGridView control properties.
The following vb.net program shows how to implement different ways of cell formatting in a
DataGridView control.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=.;Initial
Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Authors"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
DataGridView1.GridColor = Color.Red
DataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None
DataGridView1.BackgroundColor = Color.LightGray
DataGridView1.DefaultCellStyle.SelectionBackColor = Color.Red
DataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow
DataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.[True]
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DataGridView1.AllowUserToResizeColumns = False
DataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque
DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
End Sub
End Class

How to DataGridView Template

There are situations that you want greater control over the appearance of DataGridView rows
than what is provided by the various DataGridView cell style properties. The row template gives
you greater control over the appearance and behavior of rows than the RowsDefaultCellStyle
property provides. With the row template, you can set any DataGridViewRow properties,
including DefaultCellStyle. When displaying external 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 example illustrates how to use the row template to specify an initial
row height and a minimum row height and BackColor.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim row As DataGridViewRow = Me.DataGridView1.RowTemplate
row.DefaultCellStyle.BackColor = Color.Bisque
row.Height = 35
row.MinimumHeight = 20
Dim connectionString As String = "Data Source=.;Initial
Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Authors"

Dim connection As New SqlConnection(connectionString)


Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
End Sub
End Class

How to DataGridView Printing

The DataGridView control provides a customizable table for displaying data. It gives you
number of properties, methods and events to customize its appearance and behavior.
Unfortunately the DataGridView doesn't have a built in printing functionality . So here we do a
tricky way to print the content of DataGridView . Here we add a PrintDocument object to the
project and handle the PrintPage event which is called every time a new page is to be printed.
Here in the PrintPage event we create a Bitmap Object and draw the DataGridView to the
Bitmap Object.
In order to run this vb.net project you have to drag two buttons ,one for load data and one for
print command, and drag a PrintDocument control on your form . The following picture shows
how to drag PrintDocument Object to your project.

Download Source Code


Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=.;Initial
Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Authors"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
PrintDocument1.Print()
End Sub
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal
e As System.Drawing.Printing.PrintPageEventArgs) Handles
PrintDocument1.PrintPage
Dim bm As New Bitmap(Me.DataGridView1.Width, Me.DataGridView1.Height)
DataGridView1.DrawToBitmap(bm, New Rectangle(0, 0,
Me.DataGridView1.Width, Me.DataGridView1.Height))
e.Graphics.DrawImage(bm, 0, 0)
End Sub
End Class

How to Export datagridview to Excel


The DataGridView control provides a customizable table for displaying data. Displaying data in
a tabular format is a task you are likely to perform frequently. The DataGridView control is
highly configurable and extensible, and it provides many properties, methods, and events to
customize its appearance and behavior.
The following vb.net source code shows how to Export the content of a datagridview to an Excel
file.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=.;Initial
Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Authors"
Dim connection As New SqlConnection(connectionString)
Dim dataadapter As New SqlDataAdapter(sql, connection)
Dim ds As New DataSet()
connection.Open()
dataadapter.Fill(ds, "Authors_table")
connection.Close()
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Authors_table"
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Int16, j As Int16
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = DataGridView1(j,
i).Value.ToString()
Next
Next
xlWorkBook.SaveAs("c:\vb.net-informations.xls",
Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, _
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue,
misValue, misValue)
xlWorkBook.Close(True, misValue, misValue)
xlApp.Quit()
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlApp)
MessageBox.Show("Over")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)

obj = Nothing
Catch ex As Exception
obj = Nothing
MessageBox.Show("Exception Occured while releasing object " +
ex.ToString())
Finally
GC.Collect()
End Try
End Sub
End Class

How to Import data from Excel to DataGridView


The DataGridView control and its related classes are designed to be a flexible, extensible system
for displaying and editing tabular data. You can use a DataGridView control to display data with
or without an underlying data source.
The following vb.net source code shows how to Import data from an Excel file to a
DataGridView control .
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New
System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data
Source='c:\vb.net-informations.xls';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from
[Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "Net-informations.com")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)
MyConnection.Close()
End Sub
End Class

Database operations in DatagridView

The DataGridView control can display rows of data from a data source. The DataGridView 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. One very common use of the
DataGridView control is binding to a table in a database. Unbound 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 DataGridView to a database and
addnew/update or delete the database values from DataGridView.
Download Source Code
Print Source Code
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial
Catalog=pubs;Integrated Security=True"

Dim sql As String = "SELECT * FROM Stores"


Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete",
MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

You might also like