Vb.net
Vb.net
Vb.net
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
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.
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
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
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.
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
startVal=1
endVal = 5
For var = startVal To endVal
show message
Next var
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]
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) .
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.
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
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
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
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
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
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.
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
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
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
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
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
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)
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
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
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:
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 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:
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:
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:
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"
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)
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)
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, _
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
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
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
xlApp As Excel.Application
xlWorkBook As Excel.Workbook
xlWorkSheet As Excel.Worksheet
misValue As Object = System.Reflection.Missing.Value
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
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
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
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
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"
Finally
GC.Collect()
End Try
End Sub
End Class
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
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
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
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
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
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 .
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.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
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 .
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
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
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
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
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.
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.
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
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.
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.
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
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.
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
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.
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.
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:
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:
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.
Create a new VB.NET Project and accept the default settings. Create a new Dataset from Project
- Add New Item Dialogue Box.
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
NOTE
:
You have to provide the necessary databse information to Connection String.
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 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
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.
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.
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
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
You have to provide the informations like your gmail username and password , and the to
address also.
You have to provide the informations like To Address , From Address and it is very important to
enable your SMTP services in IIS .
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.
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 .
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.
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
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 .
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 .
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 .
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
Download
Chat
Chat
Chat
Server
Server
Program
Download
Client
Download
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
attachment file")
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.
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
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
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
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
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
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
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
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
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
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
" &
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
" &
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
" &
sqlReader.NextResult()
While sqlReader.Read()
MsgBox("From second SQL sqlReader.Item(1))
End While
sqlReader.NextResult()
" &
While sqlReader.Read()
MsgBox("From third SQL sqlReader.Item(1))
End While
" &
sqlReader.Close()
sqlCmd.Dispose()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
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
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
--
" &
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
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.
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.
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
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
--
" &
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
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)
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
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
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
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
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()
--
" &
--
" &
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
You have to replace the string with your real time variables.
--
Next
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
--
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class
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
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
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
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
adapter.DeleteCommand.CommandText = sql
adapter.DeleteCommand.ExecuteNonQuery()
MsgBox("Row(s) deleted !! ")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
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
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
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
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
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
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
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
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
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
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.
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.
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
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
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
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.
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.
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
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
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
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
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
End Class
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
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
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
img.Name = "img"
End Sub
End Class
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()
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
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"
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.
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
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"