Você está na página 1de 98

----------------------------------------------------------------------------------------------------------------------------------------------

1
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

.NET Framework
The .NET Framework is a managed, type-safe
environment for developing and executing
applications. The .NET Framework manages all
aspects of program execution, like, allocation of
memory for the storage of data and
instructions, granting and denying permissions
to the application, managing execution of the
application and reallocation of memory for
resources that are not needed.
The .NET Framework is designed for cross-
language compatibility. Cross-language
compatibility means, an application written in
Visual Basic .NET may reference a DLL file
written in C# (C-Sharp). A Visual Basic .NET
class might be derived from a C# class or vice
versa.
The .NET Framework consists of two main
components:
Common Language Runtime (CLR)
Class Libraries

The Common Language Runtime (CLR)
The most important concept of the .Net
Framework is the existence and functionality of
the .Net Common Language Runtime (CLR),
also called .Net Runtime for short. It is a
framework layer that resides above the OS and
handles the execution of all the .Net
applications. Our programs don't directly
communicate with the OS but go through the
CLR.





----------------------------------------------------------------------------------------------------------------------------------------------
2
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

MSIL (Microsoft Intermediate Language) Code
When we compile our .Net Program using any .Net compliant language (such as C#,
VB.Net or C++.Net) our source code does not get converted into the executable binary
code, but to an intermediate code known as MSIL which is interpreted by the Common
Language Runtime. MSIL is operating system and hardware independent code. Upon
program execution, this MSIL (intermediate code) is converted to binary executable code
(native code). Cross language relationships are possible as the MSIL code is similar for
each .Net language.

The Common Language Specification (CLS)
Earlier, we used the term '.Net Compliant Language' and stated that all the .Net compliant
languages can make use of CLR and FCL. But what makes a language a '.Net compliant'
language? The answer is the Common Language Specification (CLS). Microsoft has released
a small set of specifications that each language should meet to qualify as a .Net Compliant
Language.

The Common Type System (CTS)
.Net also defines a Common Type System (CTS). Like CLS, CTS is also a set of standards.
CTS define the basic data types that IL understands. Each .Net compliant language should
map its data types to these standard data types. This makes it possible for the 2 languages to
communicate with each other by passing/receiving parameters to and from each other. For
example, CTS defines a type, Int32, an integral data type of 32 bits (4 bytes) which is mapped
by C# through int and VB.Net through its Integer data type.

Garbage Collection (GC)
CLR also contains the Garbage Collector (GC), which runs in a low-priority thread and checks
for un-referenced, dynamically allocated memory space. If it finds some data that is no longer
referenced by any variable/reference, it re-claims it and returns it to the OS. The presence of a
standard Garbage Collector frees the programmer from keeping track of dangling data.






----------------------------------------------------------------------------------------------------------------------------------------------
3
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Framework Class Library
The Framework Class Library (FCL) is a standard library and one of two core
components of Microsoft .NET Framework. The FCL is a collection of thousands of
reusable classes (within hundreds of namespaces), interfaces and value types.
Dot net framework contains a huge collection of reusable types (class, enumerations and
structures). These types are used for common task such as IO, Memory and Thread
management. A complete object oriented toolbox is available with Visual Studio Dot Net.
Assemblies
Assemblies are the basic unit of any application. It is a logical grouping of one or more
modules or files. Smallest unit of reuse, security, and versioning. Assemblies can be
created directly by compiler (e.g. DCCIL.exe, CSC.exe, and VBC.exe). It contains resource
data (strings, icons, etc.) and is loaded at runtime based on user locale. Assemblies can be
private or shared. It can also be stored in Global Assembly Cache (GAC)
Namespaces
A namespace is a logical container for types. It is designed to eliminate name collisions. An
assembly can contribute to multiple namespaces, multiple assemblies can contributed to a
namespace
Examples
System.Drawing
System.Windows.Forms
System.IO
System.Collections
System.Data




----------------------------------------------------------------------------------------------------------------------------------------------
4
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Data Types in VB .NET

The data type of a programming element refers to what kind of data it can hold and how that data is
stored. Data types apply to all values that can be stored in computer memory or participate in the
evaluation of an expression. Every variable, literal, constant, property, procedure argument, and
procedure return value has a data type.
Type .NET Runtime type size Range
Byte System.Byte 1 byte 0 to 255 (unsigned)
SByte System.Byte 1 byte -128 to 128 (signed)
Short System.Int16 2 bytes -32768 to 32767
UShort System.Int16 2 bytes 0 to 65535
Integer System.Int32 4 bytes -2,147,483,648 to 2,147,483,647
UInteger System.Int32 4 bytes 0 to 4294967295
Long System.Int64 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ULong System.Int64 8 bytes 0 to 18446744073709551615
Single System.Single 4 bytes
Double System.Double 8 bytes
Decimal System.Decimal 12 bytes
Char System.Char 2 bytes
String System.String (class)
Date System.DateTime 8 bytes
Boolean System.Boolean 4 bytes True or False
Object System.Object (class) 4 bytes Any type can be stored in a variable of type Object









----------------------------------------------------------------------------------------------------------------------------------------------
3
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Operators
Visual Basic comes with many built-in operators that allow us to manipulate data. An operator
performs a function on one or more operands. For example, we add two variables with the "+"
addition operator and store the result in a third variable with the "=" assignment operator like this: int
x + int y = int z. The two variables (x ,y) are called operands. There are different types of operators
in Visual Basic and they are described below in the order of their precedence.
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations that involve calculation of numeric
values. The table below summarizes them:
Operator Use
^ Exponentiation
- Negation (used to reverse the sign of the given value, exp -intValue)
* Multiplication
/ Division
\ Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction

Concatenation Operators
Concatenation operators join multiple strings into a single string. There are two concatenation
operators, + and & as summarized below:
Comparison Operators
A comparison operator compares operands and returns a logical value based on whether the
comparison is true or not. The table below summarizes them:
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to
<= Less than or equal to

----------------------------------------------------------------------------------------------------------------------------------------------
6
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Logical / Bitwise Operators
The logical operators compare Boolean expressions and return a Boolean result. In short, logical
operators are expressions which return a true or false result over a conditional expression. The
table below summarizes them:
Operator Use
Not Negation
And Conjunction
AndAlso Conjunction
Or Disjunction
OrElse Disjunction
Xor Disjunction









----------------------------------------------------------------------------------------------------------------------------------------------
7
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Value Types and Reference Types
A data type is a value type if it holds the data within its own memory allocation.
A reference type contains a pointer to another memory location that holds the data.
Value Types
Value types include the following:
All numeric data types
Boolean, Char, and Date
All structures, even if their members are reference types
Enumerations, since their underlying type is always SByte, Short, Integer, Long,
Byte, UShort, UInteger, or ULong
Reference Types
Reference types include the following:
String
All arrays, even if their elements are value types
Class types, such as Form
Delegates




----------------------------------------------------------------------------------------------------------------------------------------------
8
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Scope and lifetime of a variable
A scope of a variable is the part of the program or the block of the program in which it is
visible but outside that block the variable does not exist.
Lifetime of a variable defines the time for which the variable exists in a program.
When you declare a variable within a procedure, only code within that procedure can read
or change the value of that variable: Its scope is local to that procedure. Sometimes,
however, you want to use a variable with a broader scope, one whose value is available to
all procedures within the same module, or even to all the procedures in all modules. With
Visual Basic, you can specify the scope of a variable when you declare it.
Scope of Variables

Depending on how you declare a variable, its either a procedure-level or a module-level
variable.
Scope is Private or Public

Procedure-level Variables are private to the procedure in which they appear. Not
applicable. You cant declare public variables within a procedure.
Module-level Variables are private to the module in which they appear. Variables are
available to all modules.

Lifetime of Variables
The lifetime of a variable represents the period of time during which it can hold a value. Its
value can change over its lifetime, but it always holds some value.
A variable declared at module level typically exists for the entire time your application is
running. A nonshared variable declared in a class or structure exists as a separate copy for
each instance of the class or structure in which it is declared; each such variable has the
same lifetime as its instance. However, a Shared variable has only a single lifetime, which
lasts for the entire time your application is running.
Local variables declared with Dim exist only while the procedure in which they are declared
is executing. This applies also to that procedure's arguments and to any function return.
However, if that procedure calls other procedures, the local variables retain their values
while the called procedures are running.



----------------------------------------------------------------------------------------------------------------------------------------------
9
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Data Type Conversion
In Visual Basic, data can be converted in two ways: implicitly, which means the conversion is
performed automatically, and explicitly, which means you must perform the conversion.
Implict Conversions
Let's understand implicit conversions in code. The example below declares two variable, one of type
double and the other integer. The double data type is assigned a value and is converted to integer
type. When you run the code the result displayed is an integer value, in this case the value
displayed is 132 instead of 132.31223.
Imports System.Console
Module Module1

Sub Main()
Dim d=132.31223 as Double
Dim i as Integer
i=d
WriteLine("Integer value is" & i)
End Sub

End Module
Explicit Conversions
When types cannot be implicitly converted you should convert them explicitly. This conversion is
also called as cast. Explicit conversions are accomplished using CType function.
CType function for conversion
If we are not sure of the name of a particular conversion function then we can use the CType
function. The above example with a CType function looks like this:
Imports System.Console
Module Module1

Sub Main()
Dim d As Double
d = 132.31223
Dim i As Integer
i = CType(d, i)
'two arguments, type we are converting from, to type
desired
WriteLine("Integer value is" & i)
End Sub

End Module

Below is the list of conversion functions which we can use in VB .NET.
CBool - use this function to convert to Bool data type
CByte - use this function to convert to Byte data type

----------------------------------------------------------------------------------------------------------------------------------------------
10
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
CChar - use this function to convert to Char data type
CDate - use this function to convert to Date type
CDbl - use this function to convert to Double data type
CDec - use this function to convert to Decimal data type
CInt - use this function to convert to Integer data type
CLng - use this function to convert to Long data type
CObj - use this function to convert to Object type
CShort - use this function to convert to Short data type
CSng - use this function to convert to Single data type
CString - use this function to convert to String data type
Attributes
Attributes are those that lets us specify information about the items we are using in VB .NET.
Attributes are enclosed in angle brackets(< >) and are used when VB .NET needs to know more
beyond the standard syntax.
Language Terminology
Briefly on some terminology when working with the language:
Module: Used to hold code
Variable: A named memory location of a specific data type used to hold some value
Procedure: A callable series of statements which may or may not return a value
Sub-Procedure: A procedure with no return value
Function: A procedure with return value
Methods: A procedure built into the class
Constructor: Special method used to initialize and customize the object. It has the same name as
the class
Class: An OOP class which contains data and code
Object: An instance of a class
Arrays: Programming constructs that lets us access data by numeric index
Attributes: They are the items that specify information about other items being used in VB. NET









----------------------------------------------------------------------------------------------------------------------------------------------
11
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Conditionals and Loops
S|mp|e If 1hen






If w|th L|se













Public Class MainClass
Shared Sub Main()
Dim intNumber As Integer = 27

If intNumber = 27 Then
System.Console.WriteLine("'intNumber' is,
indeed, 27!")
End If
End Sub
End Class
Public Class MainClass

Shared Sub Main(ByVal args As String())
Dim valueOne As Integer = 10
Dim valueTwo As Integer = 20
Dim valueThree As Integer = 30

If valueOne > valueTwo Then
Console.WriteLine("ValueOne: {0} larger than ValueTwo: {
1}", valueOne, valueTwo)
Else
Console.WriteLine("Nope, ValueOne: {0} is NOT larger tha
n valueTwo: {1}", valueOne, valueTwo)
End If
End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
12
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Se|ect L|se Demo


Public Class MainClass
Shared Sub Main()
'Determine which number was entered
Dim i As Integer

i = 10

Select Case i
Case 1
Console.WriteLine("The number 1 was entered")
Case 2
Console.WriteLine("The number 2 was entered")
Case 3
Console.WriteLine("The number 3 was entered")
Case 4
Console.WriteLine("The number 4 was entered")
Case 5
Console.WriteLine("The number 5 was entered")
Case Else
Console.WriteLine("A number other that 1 -
5 was entered")
End Select
End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
13
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Ior Loop Demo (Sw|tch)








Ior |oop w|th step






Wh||e Loop










Public Class MainClass
Shared Sub Main(ByVal args As String())
Dim counter As Integer

While counter <= 10
' skip remaining code in loop only if counter = 7
If counter = 7 Then
Exit While
End If

counter += 1
End While

Console.WriteLine( "counter = " & counter & _
" after exiting While structure")

End Sub
End Class

Public Class MainClass
Shared Sub Main()
'Perform a loop
For intCount As Integer = 4 To 62 Step 7
'Add the item to the list
System.Console.WriteLine(intCount)
Next
End Sub
End Class
Public Class MainClass
Shared Sub Main()

'Count from 1 to 10
For intCount As Integer = 1 To 10
System.Console.WriteLine(intCount)
Next

'Count backwards from 10 to 1
For intCount As Integer = 10 To 1 Step -1
System.Console.WriteLine(intCount)
Next
End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
14
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Do Wh||e Loop
public class MainClass
Shared Sub Main()
Dim cv As Integer = 0

Do While cv < 10
Console.WriteLine("counterVariable: {0}", cv )
cv = cv + 1
Loop
End Sub

End Class

----------------------------------------------------------------------------------------------------------------------------------------------
13
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Arrays
Arrays are programming constructs that store data and allow us to access them
by numeric index or subscript. Arrays helps us create shorter and simpler code in
many situations. Arrays in Visual Basic .NET inherit from the Array class in the
System namespace. All arrays in VB as zero based, meaning, the index of the
first element is zero and they are numbered sequentially. You must specify the
number of array elements by indicating the upper bound of the array. The upper
bound is the numder that specifies the index of the last element of the
array. Arrays are declared using Dim, ReDim, Static, Private, Public and
Protected keywords. An array can have one dimension (liinear arrays) or more
than one (multidimensional arrays). The dimensionality of an array refers to the
number of subscripts used to identify an individual element. In Visual Basic we
can specify up to 32 dimensions. Arrays do not have fixed size in Visual Basic.
The following code demonstrates arrays.
Imports System.Console
Module Module1

Sub Main()
Dim sport(5) As String
'declaring an array
sport(0) = "Soccer"
sport(1) = "Cricket"
sport(2) = "Rugby"
sport(3) = "Aussie Rules"
sport(4) = "BasketBall"
sport(5) = "Hockey"
'storing values in the array
WriteLine("Name of the Sport in the
third location" & " " & sport(2))
'displaying value from array
End Sub

End Module
Understanding the Code
The above code declared a sport array of type string like this: Dim sport(5) as
String. This sport array has 6 elements starting from sport(0) to sport(5). The
first element of an array is always referred by zero index. The image below
displays output from above code.



----------------------------------------------------------------------------------------------------------------------------------------------
16
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
You can also declare an array without specifying the number of elements on one
line, you must provide values for each element when initializing the array. The
following lines demonstrate that:
Dim Test() as Integer
'declaring a Test array
Test=New Integer(){1,3,5,7,9,}
Reinitializing Arrays
We can change the size of an array after creating them. The ReDim statement
assigns a completely new array object to the specified array variable. You
use ReDim statement to change the number of elements in an array. The
following lines of code demonstrate that. This code reinitializes the Test array
declared above.
Dim Test(10) as Integer
ReDim Test(25) as Integer
'Reinitializing the array
When using the Redim statement all the data contained in the array is lost. If you
want to preserve existing data when reinitializing an array then you should use
the Preserve keyword which looks like this:
Dim Test() as Integer={1,3,5}
'declares an array an initializes it
with three members
ReDim Preserve Test(25)
'resizes the array and retains the the
data in elements 0 to 2
Multidimensional Arrays
All arrays which were mentioned above are one dimensional or linear arrays.
There are two kinds of multidimensional arrays supported by the .NET
framework: Rectangular arrays and Jagged arrays.
Rectangular arrays
Rectangular arrays are arrays in which each member of each dimension is
extended in each other dimension by the same length. We declare a rectangular
array by specifying additional dimensions at declaration. The following lines of
code demonstrate the declaration of a multidimensional array.

----------------------------------------------------------------------------------------------------------------------------------------------
17
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Dim rectArray(4, 2) As Integer
'declares an array of 5 by 3 members which is a
15 member array
Dim rectArray(,) As Integer = {{1, 2, 3}, {12,
13, 14}, {11, 10, 9}}
'setting initial values

Jagged Arrays
Another type of multidimensional array, Jagged Array, is an array of arrays in
which the length of each array can differ. Example where this array can be used
is to create a table in which the number of columns differ in each row. Say, if
row1 has 3 columns, row2 has 3 columns then row3 can have 4 columns, row4
can have 5 columns and so on. The following code demonstrates jagged arrays.
Dim colors(2)() as String
'declaring an array of 3 arrays
colors(0)=New String(){"Red","blue","Green"}
initializing the first array to 3 members and
setting values
colors(1)=New
String(){"Yellow","Purple","Green","Violet"}
initializing the second array to 4 members
and setting values
colors(2)=New
String(){"Red","Black","White","Grey","Aqua"}
initializing the third array to 5 members and
setting values












----------------------------------------------------------------------------------------------------------------------------------------------
18
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
String Class
String represents text; that is, a series of Unicode characters.
Various properties and methods of String class are:


Chars
Gets the character at a specified character position in the string.
Dim s As String = "welcome"
Console.WriteLine(s.Chars(3)) 'c

Length
Gets the number of characters.
Dim s As String = "welcome"
Dim i As Integer
i = s.Length
Console.WriteLine ("length = " & i) '7

Comparing-Strings
The Compare method compares two strings and returns an integer value

Dim s = "welcome", s1 = "Welcome"
Dim i As Integer
i = String.Compare (s, s1)
Console.WriteLine (i) '-1
s = "welcome" s1 = "welcome"
i = String.Compare (s, s1)
Console.WriteLine (i) '0
s = "Welcome"
s1 = "welcome"
i = String.Compare (s, s1)
Console.WriteLine (i) '1

Concat
The Concat method adds strings (or objects) and returns a new string.

Dim s As String = "Hello"


Dim s1 As String = "World"
Console.WriteLine (String.Concat (s, s1))


Copy
Creates a new instance of String with the same value as a specified String.

Dim s As String = "Hello"


Dim s1 As String
s1 = s.Copy (s)

IndexOf
Return the index of the given String parameter in a Seareched String.
Dim s As String = "Welcome"
Dim s1 As String = "welcome"
Dim i As Integer = s.IndexOf ("e") '1
i = s.IndexOf ("e", 2) '6


----------------------------------------------------------------------------------------------------------------------------------------------
19
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Remove
Remove the characters from specified position in a given String.
Dim s As String = "Welcome"
Console.WriteLine(s.Remove(3, 4)) ' Wel

Replace
Replaces all occurrences of a specified character or String, with another specified character
or String.
Dim s As String = "Welcome"
Console.WriteLine (s.Replace ("e", "a")) ' Walcoma

StartWith
Determines whether the beginning of the String matches the specified String parameter.
Returns Boolean value true or false.
Dim s As String = "Welcome"
Console.WriteLine (s.StartsWith ("We")) ' true

Substring
Returns part of a string
Dim s As String = "Welcome"
Console.WriteLine(s.Substring(3)) ' come
Console.WriteLine(s.Substring(3, 3)) ' com


ToLower
Returns a String in lowercase


ToUpper
Returns a copy of the String in uppercase.
Dim s As String = "WELCOME"
Console.WriteLine (s.ToLower())
Dim s1 As String = "welcome"
Console.WriteLine (s.ToUpper())


ToString
Converts the value to a String type.


Trim
Removes all occurrences of a set of specified character from the beginning and end of the
String.

TrimEnd
Removes all occurrences of a set of specified character from the end of the String.

TrimStart
Removes all occurrences of a set of specified character from the beginning of the String.
Dim s As String = "-----------WELCOME-----------"
Console.WriteLine (s)
Console.WriteLine (s.Trim("-"))
Console.WriteLine (s.TrimEnd("-"))
Console.WriteLine (s.TrimStart("-"))


----------------------------------------------------------------------------------------------------------------------------------------------
20
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Object Oriented Programming

Class and Object
Class- A class can be considered as a generalized description of one or more objects that
share the same set of attributes and responsibilities. A class is known as a user defined data type.
Public Class Test

----- Variables
-----Methods
-----Properties
-----Events

End Class
Object- An object is an instance of the class. It is a real time entity. A class does not have its
own existence (memory allocation), objects created for those classes do. For this reason, objects
are said to be an instance of a class.
Dim obj As New Test()
------------------------------------------------------------------------------------------------------------------
Constructors
A constructor is a special member function whose task is to initialize the objects of it's class.
This is the first method that is run when an instance of a type is created. A constructor is invoked
whenever an object of its associated class is created. If a class contains a constructor, then an
object created by that class will be initialized automatically. We pass data to the constructor by
enclosing it in the parentheses following the class name when creating an object. Constructors can
never return a value, and can be overridden to provide custom intitialization functionality. In Visual
Basic we create constructors by adding a Sub procedure named New to a class. The following code
demonstrates the use of constructors in Visual Basic.
Module Module1

Sub Main()

Dim con As New Constructor(10)
WriteLine(con.display())
'storing a value in the constructor by passing a
value(10) and calling it with the
'display method
Read()

End Sub

End Module







----------------------------------------------------------------------------------------------------------------------------------------------
21
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Public Class Constructor
Public x As Integer

Public Sub New(ByVal value As Integer)
'constructor
x = value
'storing the value of x in constructor
End Sub

Public Function display() As Integer
Return x
'returning the stored value
End Function

End Class

Destructors
A destructor, also known as finalizer, is the last method run by a class. Within a destructor we can
place code to clean up the object after it is used, which might include decrementing counters or
releasing resources. We use Finalize method in Visual Basic for this and the Finalize method is
called automatically when the .NET runtime determines that the object is no longer required. When
working with destructors we need to use the overrides keyword with Finalize method as we will
override the Finalize method built into the Object class. We normally use Finalize method to
deallocate resources and inform other objects that the current object is going to be destroyed.
Because of the nondeterministic nature of garbage collection, it is very hard to determine when a
class's destructor will be called. The following code demonstrates the use of Finalize method.
Module Module1

Sub Main()
Dim obj As New Destructor()
End Sub

End Module

Public Class Destructor

Protected Overrides Sub Finalize()
Write("hello")
Read()
End Sub

End Class
When you run the above code, the word and object, obj of class, destructor is created and "Hello" is
displayed. When you close the DOS window, obj is destroyed.



----------------------------------------------------------------------------------------------------------------------------------------------
22
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Methods
A Method is a procedure built into the class. They are a series of statements that are executed
when called. Methods allow us to handle code in a simple and organized fashion. There are two
types of methods in VB .NET: those that return a value (Functions) and those that do not return a
value (Sub Procedures). Both of them are discussed below.
Sub Procedures
Sub procedures are methods which do not return a value. Each time when the Sub procedure is
called the statements within it are executed until the matching End Sub is encountered. Sub
Main(), the starting point of the program itself is a sub procedure. When the application starts
execution, control is transferred to Main Sub procedure automatically which is called by default.
Example of a Sub Procedure
Module Module1

Sub Main()
'sub procedure Main() is called by default
Display()
'sub procedure display() which we are creating
End Sub

Sub Display()
System.Console.WriteLine("Using Sub
Procedures")
'executing sub procedure Display()
End Sub
End Module
The image below displays output from above code.






----------------------------------------------------------------------------------------------------------------------------------------------
23
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Functions
Function is a method which returns a value. Functions are used to evaluate data, make calculations
or to transform data. Declaring a Function is similar to declaring a Sub procedure. Functions are
declared with the Function keyword. The following code is an example on Functions:
Imports System.Console
Module Module1

Sub Main()
Write("Sum is" & " " & Add())
'calling the function
End Sub

Public Function Add() As Integer
'declaring a function add
Dim i, j As Integer
'declaring two integers and assigning values to
them
i = 10
j = 20
Return (i + j)
'performing the sum of two integers and
returning it's value
End Function

End Module
The image below displays output from above code.


Calling Methods
A method is not executed until it is called. A method is called by referencing it's name along with
any required parameters. For example, the above code called the Add method in Sub main like this:
Write("Sum is" & " " & Add()).
Method Variables

----------------------------------------------------------------------------------------------------------------------------------------------
24
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Variables declared within methods are called method variables. They have method scope which
means that once the method is executed they are destroyed and their memory is reclaimed. For
example, from the above code (Functions) the Add method declared two integer variables i, j. Those
two variables are accessible only within the method and not from outside the method.
Parameters
A parameter is an argument that is passed to the method by the method that calls it. Parameters are
enclosed in parentheses after the method name in the method declaration. You must specify types
for these parameters. The general form of a method with parameters looks like this:
Public Function Add(ByVal x1 as Integer, ByVal y1 as Integer)
------------
Implementation
------------
End Function


----------------------------------------------------------------------------------------------------------------------------------------------
23
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Inheritance
A key feature of OOP is reusability. It's always time saving and useful if we can reuse something
that already exists rather than trying to create the same thing again and again. Reusing the
class that is tested, debugged and used many times can save us time and effort of developing
and testing it again. Once a class has been written and tested, it can be used by other programs
to suit the program's requirement. This is done by creating a new class from an existing class.
The process of deriving a new class from an existing class is called Inheritance. The old class is
called the base class and the new class is called derived class. The derived class inherits some
or everything of the base class. In Visual Basic we use the Inherits keyword to inherit one class
from other. The general form of deriving a new class from an existing class looks as follows:
Public Class One
---
---
End Class

Public Class Two
Inherits One
---
---
End Class
Using Inheritance we can use the variables, methods, properties, etc, from the base class and add
more functionality to it in the derived class. The following code demonstrates the process of
Inheritance in Visual Basic.












Module Module1
Sub Main()
Dim ss As New Two()
WriteLine(ss.sum())
Read()
End Sub
End Module

Public Class One
Public i As Integer = 10
Public j As Integer = 20

Public Function add() As Integer
Return i + j
End Function
End Class

Public Class Two
Inherits One
class one
Public k As Integer = 100

Public Function sum() As Integer
'using the variables, function from base
class and adding more functionality
Return i + j + k
End Function
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
26
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Polymorphism
Method Overloading
Polymorphism is one of the crucial features of OOP. It means "one name, multiple forms". It is
also called as Overloading which means the use of same thing for different purposes. Using
Polymorphism we can create as many functions we want with one function name but with different
argument list. The function performs different operations based on the argument list in the function
call. The exact function to be invoked will be determined by checking the type and number of
arguments in the function.
The following code demonstrates the implementation of Polymorphism.
Module Module1

Sub Main()
Dim sam As New Sample ()

Console.WriteLine(sam.add(10))
'calls the function with one argument
Console.WriteLine(sam.add(10, 20))
'calls the function with two arguments
Console.WriteLine(sam.add(10, 20, 30))
'calls the function with three arguments
Read()
End Sub

End Module

Public Class Sample

Public Function add(ByVal i As Integer) As Integer
'function with one argument
Return i
End Function

Public Function add(ByVal i As Integer, ByVal j As Integer)
As Integer
'function with two arguments
Return i + j
End Function

Public Function add(ByVal i As Integer, ByVal j As Integer,
ByVal k As Integer) As Integer
'function with three arguments
Return i + j + k
End Function

End Class




----------------------------------------------------------------------------------------------------------------------------------------------
27
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Method Overriding
Overriding is an important concept in Object Oriented Technology.
Method overriding is using same method name along with same number & type of arguments in
base as well as derived class.
Method overriding is a language feature that allows a subclass to override a specific implementation
of a method that is already provided by one of its super-classes.
A subclass can give its own definition of methods but need to have the same signature as the
method in its super-class. This means that when overriding a method the subclass's method has to
have the same name and parameter list as the super-class's overridden method.











Overloading v/s Overriding
Overloading deals with multiple methods in the same class with the same name but
different signatures
Overriding deals with two methods, one in a parent class and one in a child class, that
have the same signature
Overloading lets you define a similar operation in different ways for different data
Overriding lets you define a similar operation in different ways for different object types




'The Original Class
Public Class MyBaseClass
Public Overridable Function MyFunc(ByVal X as Integer,
ByVal Y as Integer) as Integer
Retun X * Y
End sub
End Class

'The Derived Class
Public Class MyNewClass
Inherits MyBaseClass

Public Overrides Function MyFunc(ByVal X as Integer, ByVal Y as
Integer) as Integer
'Take note: It accepts and return same values but it changes
the process
Retun X + Y
End sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
28
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Abstract Classes
An abstract class is the one that is not used to create objects. An abstract class is designed to act
as a base class (to be inherited by other classes). Abstract class is a design concept in program
development and provides a base upon which other classes are built. Abstract classes are similar to
interfaces. After declaring an abstract class, it cannot be instantiated on its own, it must be
inherited. Like interfaces, abstract classes can specify members that must be implemented in
inheriting classes. Unlike interfaces, a class can inherit only one abstract class. Abstract classes
can only specify members that should be implemented by all inheriting classes.
Creating Abstract Classes
In Visual Basic .NET we create an abstract class by using the MustInherit keyword. An abstract
class like all other classes can implement any number of members. Members of an abstract class
can either be Overridable (all the inheriting classes can create their own implementation of the
members) or they can have a fixed implementation that will be common to all inheriting members.
Abstract classes can also specify abstract members. Like abstract classes, abstract members also
provide no details regarding their implementation. Only the member type, access level, required
parameters and return type are specified. To declare an abstract member we use the MustOverride
keyword. Abstract members should be declared in abstract classes.
Implementing Abstract Class
When a class inherits from an abstract class, it must implement every abstract member defined by
the abstract class. Implementation is possible by overriding the member specified in the abstract
class. The following code demonstrates the declaration and implementation of an abstract class.
Module Module1

Public MustInherit Class AbstractClass
'declaring an abstract class with MustInherit keyword
Public MustOverride Function Add() As Integer
Public MustOverride Function Mul() As Integer
'declaring two abstract members with MustOverride
keyword
End Class

Public Class AbstractOne
Inherits AbstractClass
'implementing the abstract class by inheriting
Dim i As Integer = 20
Dim j As Integer = 30
'declaring two integers

Public Overrides Function Add() As Integer
Return i + j
End Function
'implementing the add method

Public Overrides Function Mul() As Integer
Return i * j
End Function
'implementing the mul method


----------------------------------------------------------------------------------------------------------------------------------------------
29
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
End Class

Sub Main()
Dim abs As New AbstractOne()
'creating an instance of AbstractOne
WriteLine("Sum is" & " " & abs.Add())
WriteLine("Multiplication is" & " " & abs.Mul())
'displaying output
Read()
End Sub

End Module





















----------------------------------------------------------------------------------------------------------------------------------------------
30
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Interfaces
An interface is a skeleton of rules that must be enforced in the inherited types. An interface contains only the
signatures of methods, properties, events, indexers, and delegates.
Important Rules of Interfaces
A user defined data type similar to class but contains all abstract methods.
All methods are abstract and public by default.
All such methods are overridden in child class.
Allows to implement the multiple inheritance.
A class can inherit only one other class but any number of interfaces.
implements keyword to implement the interface.
use the Interface keyword to create an interface.
An interface can inherit from one or more base interfaces.
An interface or class inherited from more than one base interfaces is called multiple inheritance.
A derived class must implement all interface members.
Interfaces allow us to create definitions for component interaction. They also provide another way of
implementing polymorphism. Through interfaces, we specify methods that a component must implement
without actually specifying how the method is implemented. We just specify the methods in an interface and
leave it to the class to implement those methods. Visual Basic .NET does not support multiple inheritance
directly but using interfaces we can achieve multiple inheritance. We use the Interface keyword to create an
interface and implements keyword to implement the interface. Once you create an interface you need to
implement all the methods specified in that interface. The following code demonstrates the use of interface.
Imports System.Console

Module Module1
Sub Main()
Dim OneObj As New One()
Dim TwoObj As New Two()
'creating objects of class One and Two
OneObj.disp()
OneObj.multiply()
TwoObj.disp()
TwoObj.multiply()
'accessing the methods from classes as specified in the
interface
End Sub
End Module

Public Interface Test
'creating an Interface named Test
Sub disp()
Function Multiply() As Double
'specifying two methods in an interface
End Interface







----------------------------------------------------------------------------------------------------------------------------------------------
31
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Public Class One
Implements Test
'implementing interface in class One

Public i As Double = 12
Public j As Double = 12.17

Sub disp() Implements Test.disp
'implementing the method specified in interface
WriteLine("sum of i+j is" & i + j)
Read()
End Sub

Public Function multiply() As Double Implements Test.Multiply
'implementing the method specified in interface
WriteLine(i * j)
Read()
End Function
End Class



Public Class Two
Implements Test
'implementing the interface in class Two

Public a As Double = 20
Public b As Double = 32.17

Sub disp() Implements Test.disp
WriteLine("Welcome to Interfaces")
Read()
End Sub

Public Function multiply() As Double Implements Test.Multiply
WriteLine(a * b)
Read()
End Function
End Class











----------------------------------------------------------------------------------------------------------------------------------------------
32
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Access Specifiers
Access Specifies describes as the scope of accessibility of an Object and its members. We can
control the scope of the member object of a class using access specifies. We are using access
specifies for providing security of our applications.
Public Applied at the class level and is the most common specifier. Public Classes are
classes that are intended to be used by any consumer.
Public Class PubClass
Public i As Integer=5
End Class

Protected - can only be applied to Nested Classes. Are only accessible within the class and
within the child classes.
Public Class HasProtected
Protected Class ProtectedClass
Protected i As Integer=5
End Class
End Class

Friend Are accessible only within the program in which they are defined. If you add the
Friend access specifier to a class definition, instance of that class can only be created from
within th same program.
Friend Class FriendClass
Public Shared Sub PublicMethod()
MsgBox("FriendClass.PublicMethod")
End Sub
End Class

Private Can only be applied to a nested class. A Private nested class represents
implementation details of the class. When you have complex problem that requires
more problem solving horsepower then simple methods can provided, defining a
nested private class that implements the abstraction.
Public Class HasPrivate
Private Class PrivateClass
Private p As Integer
End Class
End Class



----------------------------------------------------------------------------------------------------------------------------------------------
33
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Collections
Visual Basic .NET Collections are data structures that holds data in different ways for flexible
operations. The important data structures in the Collations are ArrayList, HashTable, Stack and
Queue etc. In the following chapters you can see how to manage these data structures in your
visual basic.net (vb.net) programs.

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.
ush: Add (ush) an |tem |n the stack data structure
5tock.losb(Object)
op : op return the |tem |ast Item to |nsert |n stack
5tock.lop()














Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click

Dim stackTable As New Stack

stackTable.Push("Sun")
stackTable.Push("Mon")
stackTable.Push("Tue")
stackTable.Push("Wed")
stackTable.Push("Thu")
stackTable.Push("Fri")
stackTable.Push("Sat")

If stackTable.Contains("Wed") Then
MsgBox(stackTable.Pop())
Else
MsgBox("not exist")
End If

End Sub
End Class


----------------------------------------------------------------------------------------------------------------------------------------------
34
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
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.
Lnqueue : Add an Item |n ueue
Stack.Enqueue(Object)
Dequeue : kemove the o|dest |tem from ueue (we don't get the |tem |ater)
Stack.Dequeue()



















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


----------------------------------------------------------------------------------------------------------------------------------------------
33
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
ArrayList
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 .
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 ?
ArrayList.add(Item)











Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click

Dim i As Integer

Dim ItemList As New ArrayList()
ItemList.Add("Item4")
ItemList.Add("Item5")
ItemList.Add("Item2")
ItemList.Add("Item1")
ItemList.Add("Item3")

MsgBox("Shows Added Items")

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

'insert an item
ItemList.Insert(3, "Item6")
'sort itemms in an arraylist
ItemList.Sort()
'remove an item
ItemList.Remove("Item1")
'remove item from a specified index
ItemList.RemoveAt(3)

MsgBox("Shows final Items the ArrayList")

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

End Sub
End Class


----------------------------------------------------------------------------------------------------------------------------------------------
36
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
HashTable
HashTable stores a Key Value pair type collection of data. We can retrieve items
from hashTable to provide the key. Both key and value are Objects.

Add : To add a pair of value in HashTable

HashTable.Add(Key,Value)
Key : The Key value
Value : The value of corrosponding key











Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click

Dim weeks As New Hashtable
Dim day As DictionaryEntry

weeks.Add("1", "Sun")
weeks.Add("2", "Mon")
weeks.Add("3", "Tue")
weeks.Add("4", "Wed")
weeks.Add("5", "Thu")
weeks.Add("6", "Fri")
weeks.Add("7", "Sat")

'Display a single Item
MsgBox(weeks.Item("5"))

'Search an Item
If weeks.ContainsValue("Tue") Then
MsgBox("Find")
Else
MsgBox("Not find")
End If

'remove an Item
weeks.Remove("3")
'Display all key value pairs

For Each day In weeks
MsgBox(day.Key " -- " day.Value)
Next

End Sub
End Class


----------------------------------------------------------------------------------------------------------------------------------------------
37
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Exception Handling
Exception handling is an in built mechanism in .NET framework to detect and handle
run time errors. The .NET framework contains lots of standard exceptions. The
exceptions are anomalies that occur during the execution of a program. They can be
because of user, logic or system errors. If a user (programmer) do not provide a
mechanism to handle these anomalies, the .NET run time environment provide a
default mechanism, which terminates the program execution.

VB.NET provides three keywords try, catch and finally to do exception handling. The try
encloses the statements that might throw an exception whereas catch handles an
exception if one exists. The finally can be used for doing any clean up process.

The general form try-catch-finally in VB.NET is shown below.

Try
' Statement which can cause an exception.
Catch x As Type
' Statements for handling the exception
Finally
End Try 'Any cleanup code

If any exception occurs inside the try block, the control transfers to the appropriate
catch block and later to the finally block.

But in VB.NET, both catch and finally blocks are optional. The try block can exist either
with one or more catch blocks or a finally block or with both catch and finally blocks.

If there is no exception occurred inside the try block, the control directly transfers to
finally block. We can say that the statements inside the finally block is executed
always. Note that it is an error to transfer control out of a finally block by using break,
continue, return or goto.

In VB.NET, exceptions are nothing but objects of the type Exception. The Exception is
the ultimate base class for any exceptions in VB.NET. The VB.NET itself provides couple
of standard exceptions. Or even the user can create their own exception classes,
provided that this should inherit from either Exception class or one of the standard
derived classes of Exception class like DivideByZeroExcpetion ot ArgumentException
etc.

Uncaught Exceptions

The following program will compile but will show an error during execution. The
division by zero is a runtime anomaly and program terminates with an error message.
Any uncaught exceptions in the current context propagate to a higher context and
looks for an appropriate catch block to handle it. If it can't find any suitable catch
blocks, the default mechanism of the .NET runtime will terminate the execution of the
entire program.


----------------------------------------------------------------------------------------------------------------------------------------------
38
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 100 / x
Console.WriteLine(div)
End Sub 'Main
End Class 'MyClient

The modified form of the above program with exception handling mechanism is as
follows. Here we are using the object of the standard exception class
DivideByZeroException to handle the exception caused by division by zero.
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("This line in not executed")
Catch de As DivideByZeroException
onsole.WriteLine("Exception occured")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient

In the above case the program do not terminate unexpectedly. Instead the program
control passes from the point where exception occurred inside the try block to the
catch blocks. If it finds any suitable catch block, executes the statements inside that
catch and continues with the normal execution of the program statements.

If a finally block is present, the code inside the finally block will get also be executed.
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Catch de As DivideByZeroException
Console.WriteLine("Exception occured")
Finally
Console.WriteLine("Finally Block")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient

----------------------------------------------------------------------------------------------------------------------------------------------
39
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Remember that in VB.NET, the catch block is optional. The following program is
perfectly legal in VB.NET.
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Finally
Console.WriteLine("Finally Block")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient
But in this case, since there is no exception handling catch block, the execution will get
terminated. But before the termination of the program statements inside the finally
block will get executed. In VB.NET, a try block must be followed by either a catch or
finally block.

Multiple Catch Blocks

A try block can throw multiple exceptions, which can handle by using multiple catch
blocks. Remember that more specialized catch block should come before a generalized
one. Otherwise the compiler will show a compilation error.
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Catch de As DivideByZeroException
Console.WriteLine("DivideByZeroException")
Catch ee As Exception
Console.WriteLine("Exception")
Finally
Console.WriteLine("Finally Block")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient




----------------------------------------------------------------------------------------------------------------------------------------------
40
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Catching all Exceptions

By providing a catch block without a brackets or arguments, we can catch all
exceptions occurred inside a try block. Even we can use a catch block with an
Exception type parameter to catch all exceptions happened inside the try block since in
VB.NET, all exceptions are directly or indirectly inherited from the Exception class.
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Catch
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient
The following program handles all exception with Exception object.
Imports System
Class MyClient
Public Shared Sub Main()
Dim x As Integer = 0
Dim div As Integer = 0
Try
div = 100 / x
Console.WriteLine("Not executed line")
Catch e As Exception
Console.WriteLine("oException")
End Try
Console.WriteLine("Result is {0}", div)
End Sub 'Main
End Class 'MyClient
Throwing an Exception

In VB.NET, it is possible to throw an exception programmatically. The 'throw' keyword
is used for this purpose. The general form of throwing an exception is as follows.
Throw exception_obj
For example the following statement throw an ArgumentException explicitly.
Throw New ArgumentException("Exception")

Imports System
Class MyClient
Public Shared Sub Main()
Try
Throw New DivideByZeroException("Invalid Division")

----------------------------------------------------------------------------------------------------------------------------------------------
41
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Catch e As DivideByZeroException
Console.WriteLine("Exception")
End Try
Console.WriteLine("LAST STATEMENT")
End Sub 'Main
End Class 'MyClient
User-defined Exceptions

In VB.NET, it is possible to create our own exception class. But Exception must be the
ultimate base class for all exceptions in VB.NET. So the user-defined exception classes
must inherit from either Exception class or one of its standard derived classes.
Imports System
Class MyException
Inherits Exception
Public Sub New(ByVal str As String)
Console.WriteLine("User defined exception")
End Sub 'New
End Class 'MyException
Class MyClient
Public Shared Sub Main()
Try
Throw New MyException("RAJESH")
Catch e As Exception
Console.WriteLine(("Exception caught here" + e.ToString()))
End Try
Console.WriteLine("LAST STATEMENT")
End Sub 'Main
End Class 'MyClient


----------------------------------------------------------------------------------------------------------------------------------------------
42
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Windows Controls
TextBox Control
Windows users should be familiar with textboxes. This control looks like a box and accepts input
from the user. The TextBox is based on the TextBoxBase class which is based on the Control class.
TextBoxes are used to accept input from the user or used to display text. By default we can enter up
to 2048 characters in a TextBox but if the Multiline property is set to True we can enter up to 32KB
of text.
Some Notable Properties:
Some important properties in the Behavior section of the Properties Window for TextBoxes.
Enabled: Default value is True. To disable, set the property to False.
Multiline: Setting this property to True makes the TextBox multiline which allows to accept
multiple lines of text. Default value is False.
PasswordChar: Used to set the password character. The text displayed in the TextBox will
be the character set by the user. Say, if you enter *, the text that is entered in the TextBox
is displayed as *.
ReadOnly: Makes this TextBox readonly. It doesn't allow to enter any text.
Visible: Default value is True. To hide it set the property to False.
Important properties in the Appearance section
TextAlign: Allows to align the text from three possible options. The default value is left and
you can set the alignment of text to right or center.
Scrollbars: Allows to add a scrollbar to a Textbox. Very useful when the TextBox is
multiline. You have four options with this property. Options are are None, Horizontal,
Vertical and Both. Depending on the size of the TextBox anyone of those can be used.








----------------------------------------------------------------------------------------------------------------------------------------------
43
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Button Control
One of the most popular controls in Visual Basic is the Button Control (previously
Command Control). They are the controls which we click and release to perform some
action. Buttons are used mostly for handling events in code, say, for sending data entered
in the form to the database and so on. The default event of the Button is the Click event and
the Button class is based on the ButtonBase class which is based on the Control class.
Button Event
The default event of the Button is the Click event. When a Button is clicked it responds with
the Click Event.
Button Properties
Text : Gets/Sets the text for this control
BackColor : Gets/Sets the background color
ForeColor : Gets/Sets the foreground color of the control
TextAlign: Allows to align the text from three possible options. The default
value is left and you can set the alignment of text to right or center.
Font : Gets/Sets the font for the control
Dock : Resizes size of control as per the seize of parent control
Enabled: Default value is True. To disable, set the property to False.
Visible: Default value is True. To hide it set the property to False.













----------------------------------------------------------------------------------------------------------------------------------------------
44
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
RichTextBox
RichTextBoxes are similar to TextBoxes but they provide some advanced features over
the standard TextBox. RichTextBox allows formatting the text, say adding colors,
displaying particular font types and so on. The RichTextBox, like the TextBox is based
on the TextBoxBase class which is based on the Control class. These RichTextBoxes
came into existence because many word processors these days allow us to save text in
a rich text format. With RichTextBoxes we can also create our own word processors.
We have two options when accessing text in a RichTextBox, text and rtf (rich text
format). Text holds text in normal text and rtf holds text in rich text format.
Text : Gets/Sets the text for this control
BackColor : Gets/Sets the background color
ForeColor : Gets/Sets the foreground color of the control
TextAlign: Allows to align the text from three possible options. The
default value is left and you can set the alignment of text to right or
center.
Font : Gets/Sets the font for the control
Dock : Resizes size of control as per the seize of parent control
Enabled: Default value is True. To disable, set the property to False.
Visible: Default value is True. To hide it set the property to False.

Code for creating bold and italic text in a RichTextBox
Drag a RichTextBox (RichTextBox1) and a Button (Button1) onto the form. Enter some
text in RichTextBox1, say, "We are working with RichTextBoxes". Paste the following
code in the click event of Button1. The following code will search for text we mention in
code and sets it to be displayed as Bold or Italic based on what text is searched for.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click

RichTextBox1.SelectionStart = RichTextBox1.Find("are")
'using the Find method to find the text "are" and setting it's
'return property to SelectionStart which selects the text to format
Dim ifont As New Font(RichTextBox1.Font, FontStyle.Italic)
'creating a new font object to set the font style
RichTextBox1.SelectionFont = ifont
'assigning the value selected from the RichTextBox the font style
RichTextBox1.SelectionStart = RichTextBox1.Find("working")
Dim bfont As New Font(RichTextBox1.Font, FontStyle.Bold)
RichTextBox1.SelectionFont = bfont

End Sub
When you run the above code and click Button1, the text "are" is displayed in Italic and
the text "working" is displayed in Bold font. The image below displays the output.


----------------------------------------------------------------------------------------------------------------------------------------------
43
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Code for Setting the Color of Text
Lets work with previous example. Code for setting the color for particular text looks like
this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _
System.EventArgs) Handles Button1.Click

RichTextBox1.SelectionStart = RichTextBox1.Find("are")
'using the Find method to find the text "are" and setting it's return
'property to SelectionStart which selects the text
RichTextBox1.SelectionColor = Color.Blue
'setting the color for the selected text with SelectionColor property
RichTextBox1.SelectionStart = RichTextBox1.Find("working")
RichTextBox1.SelectionColor = Color.Yellow

End Sub



----------------------------------------------------------------------------------------------------------------------------------------------
46
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
CheckBox
CheckBoxes are those controls which gives us an option to select, say, Yes/No or
True/False. A checkbox is clicked to select and clicked again to deselect some option.
When a checkbox is selected a check (a tick mark) appears indicating a selection. The
CheckBox control is based on the TextBoxBase class which is based on the Control class.
Important properties of the CheckBox in the Appearance section of the properties window
are:
Appearance: Default value is Normal. Set the value to Button if you want the CheckBox to
be displayed as a Button.
BackgroundImage: Used to set a background image for the checkbox.
CheckAlign: Used to set the alignment for the CheckBox from a predefined list.
Checked: Default value is False, set it to True if you want the CheckBox to be displayed as
checked.
CheckState: Default value is Unchecked. Set it to True if you want a check to appear.
When set to Indeterminate it displays a check in gray background.

Important property in the Behavior section of the properties window is the ThreeState
property which is set to False by default. Set it to True to specify if the Checkbox can allow
three check states than two.
CheckBox Event
The default event of the CheckBox is the CheckedChange event which looks like this in
code:
Private Sub CheckBox1_CheckedChanged(ByVal sender As
System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged

End Sub

Working with CheckBoxes
Lets work with an example. Drag a CheckBox (CheckBox1), TextBox (TextBox1) and a
Button (Button1) from the Toolbox.
Code to display some text when the Checkbox is checked
Private Sub CheckBox1_CheckedChanged(ByVal sender As
System.Object, _
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
TextBox1.Text = "CheckBox Checked"
End Sub


----------------------------------------------------------------------------------------------------------------------------------------------
47
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Code to check a CheckBox's state
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click

If CheckBox1.Checked = True Then
TextBox1.Text = "Checked"
Else
TextBox1.Text = "UnChecked"
End If

End Sub
Creating a CheckBox in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles_ MyBase.Load

Dim CheckBox1 As New CheckBox()
CheckBox1.Text = "Checkbox1"
CheckBox1.Location = New Point(100, 50)
CheckBox1.Size = New Size(95, 45)
Me.Controls.Add(CheckBox1)

End Sub













----------------------------------------------------------------------------------------------------------------------------------------------
48
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
RadioButton
RadioButtons are similar to CheckBoxes but RadioButtons are displayed as rounded
instead of boxed as with a checkbox. Like CheckBoxes, RadioButtons are used to select
and deselect options but they allow us to choose from mutually exclusive options. The
RadioButton control is based on the ButtonBase class which is based on the Control class.
A major difference between CheckBoxes and RadioButtons is, RadioButtons are mostly
used together in a group.
Important properties of the RadioButton in the Appearance section of the properties window
are:
Appearance: Default value is Normal. Set the value to Button if you want the RadioButton
to be displayed as a Button.
BackgroundImage: Used to set a background image for the RadioButton.
CheckAlign: Used to set the alignment for the RadioButton from a predefined list.
Checked: Default value is False, set it to True if you want the RadioButton to be displayed
as checked.

RadioButton Event
The default event of the RadioButton is the CheckedChange event which looks like this in
Working with Examples
Drag a RadioButton (RadioButton1), TextBox (TextBox1) and a Button (Button1) from the
Toolbox.
Code to display some text when the RadioButton is selected
Private Sub RadioButton1_CheckedChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
RadioButton1.CheckedChanged

TextBox1.Text = "RadioButton Selected"
End Sub

Code to check a RadioButton's state
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

If RadioButton1.Checked = True Then
TextBox1.Text = "Selected"
Else
TextBox1.Text = "Not Selected"
End If

End Sub


----------------------------------------------------------------------------------------------------------------------------------------------
49
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Creating a RadioButton in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles_ MyBase.Load

Dim RadioButton1 As New RadioButton()
RadioButton1.Text = "RadioButton1"
RadioButton1.Location = New Point(120,60)
RadioButton1.Size = New Size(100, 50)
Me.Controls.Add(RadioButton1)

End Sub



----------------------------------------------------------------------------------------------------------------------------------------------
30
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
ListBox
The ListBox control displays a list of items from which we can make a selection. We can
select one or more than one of the items from the list. The ListBox control is based on the
ListControl class which is based on the Control class.
Notable Properties of the ListBox
In the Behavior Section
HorizontalScrollbar: Displays a horizontal scrollbar to the ListBox. Works when the
ListBox has MultipleColumns.
MultiColumn: The default value is set to False. Set it to True if you want the list box to
display multiple columns.
ScrollAlwaysVisible: Default value is set to False. Setting it to True will display both
Vertical and Horizontal scrollbar always.
SelectionMode: Default value is set to one. Select option None if you do not any item to
be selected. Select it to MultiSimple if you want multiple items to be selected. Setting it to
MultiExtended allows you to select multiple items with the help of Shift, Control and arrow
keys on the keyboard.
Sorted: Default value is set to False. Set it to True if you want the items displayed in the
ListBox to be sorted by alphabetical order.
In the Data Section
Notable property in the Data section of the Properties window is the Items property. The
Items property allows us to add the items we want to be displayed in the list box. Doing so
is simple, click on the ellipses to open the String Collection Editor window and start entering
what you want to be displayed in the ListBox. After entering the items click OK and doing
that adds all the items to the ListBox.
ListBox Event
The default event of ListBox is the SelectedIndexChanged which looks like this in code:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles
ListBox1.SelectedIndexChanged

End Sub
Working with ListBoxes
Drag a TextBox and a ListBox control to the form and add some items to the ListBox with
it's items property.



----------------------------------------------------------------------------------------------------------------------------------------------
31
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Referring to Items in the ListBox
Items in a ListBox are referred by index. When items are added to the ListBox they are
assigned an index. The first item in the ListBox always has an index of 0 the next 1 and so
on.
Code to display the index of an item
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As
System.Object,ByVal e As System.EventArgs) Handles
ListBox1.SelectedIndexChanged

TextBox1.Text = ListBox1.SelectedIndex
'using the selected index property of the list box to select the index

End Sub

When you run the code and select an item from the ListBox, it's index is displayed in the
textbox.
Counting the number of Items in a ListBox
Add a Button to the form and place the following code in it's click event.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button1.Click

TextBox1.Text = ListBox1.Items.Count
'counting the number of items in the ListBox with the Items.Count

End Sub
When you run the code and click the Button it will display the number of items available in
the ListBox.
Code to display the item selected from ListBox in a TextBox
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As
System.Object,ByVal e As System.EventArgs) Handles
ListBox1.SelectedIndexChanged

TextBox1.Text = ListBox1.SelectedItem
'using the selected item property

End Sub
When you run the code and click an item in the ListBox that item will be displayed in the
TextBox.



----------------------------------------------------------------------------------------------------------------------------------------------
32
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Code to Remove items from a ListBox
You can remove all items or one particular item from the list box.
Code to remove a particular item
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click

ListBox1.Items.RemoveAt(4)
'removing an item by specifying it's index

End Sub
Code to Remove all items
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

ListBox1.Items.Clear()
'using the clear method to clear the list box

End Sub




----------------------------------------------------------------------------------------------------------------------------------------------
33
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
ComboBox
ComboBox is a combination of a TextBox and a ListBox. The ComboBox displays an
editing field (TextBox) combined with a ListBox allowing us to select from the list or to enter
new text. ComboBox displays data in a drop-down style format. The ComboBox class is
derived from the ListBox class.
Notable properties of the ComboBox
The DropDownStyle property in the Appearance section of the properties window allows
us to set the look of the ComboBox. The default value is set to DropDown which means that
the ComboBox displays the Text set by it's Text property in the Textbox and displays it's
items in the DropDownListBox below. Setting it to simple makes the ComboBox to be
displayed with a TextBox and the list box which doesn't drop down. Setting it to
DropDownList makes the ComboBox to make selection only from the drop down list and
restricts you from entering any text in the textbox.
We can sort the ComboBox with it's Sorted property which is set to False by Default.
We can add items to the ComboBox with it's Items property.

ComboBox Event
The default event of ComboBox is SelectedIndexChanged which looks like this in code:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object,_
ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged

End Sub
Working with ComboBoxes
Drag a ComboBox and a TextBox control onto the form. To display the selection made in
the ComboBox in the Textbox the code looks like this:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As
System.Object,_
ByVal e As System.EventArgs) Handles
ComboBox1.SelectedIndexChanged
TextBox1.Text = ComboBox1.SelectedItem
'selecting the item from the ComboBox with selected item
property
End Sub
Removing items from a ComboBox
You can remove all items or one particular item from the list box part of the ComboxBox.
Code to remove a particular item by it's Index number looks like this:

----------------------------------------------------------------------------------------------------------------------------------------------
34
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As_
System.EventArgs) Handles Button1.Click
ComboBox1.Items.RemoveAt(4)
'removing an item by specifying it's index
End Sub
Code to remove all items from the ComboBox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As_
System.EventArgs) Handles Button1.Click
ComboBox1.Items.Clear()
'using the clear method to clear the list box
End Sub




----------------------------------------------------------------------------------------------------------------------------------------------
33
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
TreeView
The tree view control is used to display a hierarchy of nodes (both parent, child). You can
expand and collpase these nodes by clicking them. This control is similar to Windows
Explorer which displays a tree view in it's left pane to list all the folders on the hard disk.
Properties of TreeView
Bounds: Gets the actual bound of the tree node
Checked: Gets/Sets whether the tree node is checked
FirstNode: Gets the first child tree node
FullPath: Gets the path from the root node to the current node
ImageIndex: Gets/Sets the image list index of the image displayed for a node
Index: Gets the location of the node in the node collection
IsEditing: Gets whether the node can be edited
IsExpaned: Gets whether the node is expaned
IsSelected: Gets whether the node is selected
LastNode: Gets the last child node
NextNode: Gets the next sibling node
NextVisibleNode: Gets the next visible node
NodeFont: Gets/Sets the font for nodes
Nodes: Gets the collection of nodes in the current node
Parent: Gets the parent node of the current node
PrevNode: Gets the previous sibling node
PrevVisibleNode: Gets the previous visible node
TreeView: Gets the node's parent tree view
TreeView Event
Default event of the Tree View control is the AfterSelect event which looks like this in code:
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal
e As_
System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect

End Sub







----------------------------------------------------------------------------------------------------------------------------------------------
36
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Panel
Panels are those controls which contain other controls, for example, a set of radio buttons,
checkboxes, etc. Panels are similar to Groupboxes but the difference, Panels cannot
display captions where as GroupBoxes can and Panels can have scrollbars where as
GroupBoxes can't. If the Panel's Enabled property is set to False then the controls which
the Panel contains are also disabled. Panels are based on the ScrollableControl class.
Notable property of the Panel control in the appearance section is the BorderStyle property.
The default value of the BorderStyle property is set to None. You can select from the
predefined list to change a Panels BorderStyle.
Notable property in the layout section is the AutoScroll property. Default value is set to
False. Set it to True if you want a scrollbar with the Panel.
GroupBox Control
As said above, Groupboxes are used to Group controls. GroupBoxes display a frame
around them and also allows to display captions to them which is not possible with the
Panel control. The GroupBox class is based on the Control class.

PictureBox Control
PictureBoxes are used to display images on them. The images displayed can be anything
varying from Bitmap, JPEG, GIF, PNG or any other image format files. The PictureBox
control is based on the Control class.
Notable property of the PictureBox Control in the Appearance section of the properties
window is the Image property which allows to add the image to be displayed on the
PictureBox.
Adding Images to PictureBox
Images can be added to the PictureBox with the Image property from the Properties
window or by following lines of code.
Private Sub Button1_Click(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles Button1.Click

PictureBox1.Image = New System.Drawing.Bitmap("figure2.bmp")

End Sub



----------------------------------------------------------------------------------------------------------------------------------------------
37
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
1|mer Contro|

1he 1lmer ConLrol allows you Lo seL speclflc Llme lnLervals unLll some code has Lo be execuLed.
Step1: Open VB.Net and create a new windows application.

Step2: Add a listbox to the form. We are going to use the listbox to additems to it every
timer control gets executed.

Step3: Add the timer control to your form. Notice how the timer control is not shown on the
form but instead in a different panel at the bottom.





Step4: Click on the timer control and press the F4 key to bring up the timer's property
window , change the timer's enabled property from false to true and also change the timer's
interval property to 1000 which is about one second.

Step5: Double click the timer control to bring up the timer's tick event. In the tick event we
are going to add the code:
Public Class Form1
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Timer1.Tick
ListBox1.Items.Add(ListBox1.Items.Count)
End Sub
End Class


----------------------------------------------------------------------------------------------------------------------------------------------
38
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
What this does is add to our listbox the number of items in the listbox each time the tick
event executes which we set earlier to 1000 or every second.

Step6: Run the program by pressing F5 keyword on your keyboard and notice how the
numbers get added to the listbox. With the help of the scroll bar you can see the
numbers till end.
The timer control allows you to set specific time intervals until some code has to be executed.
Here is how you program the timer control in VB.net



----------------------------------------------------------------------------------------------------------------------------------------------
39
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
L|stV|ew Contro|

1he llsL vlew conLrol ls baslcally and advanced LlsL8ox. 1hls conLrol allows you Lo add rows of daLa, buL lL also
supporLs large and small lcons, mulLlple columns, auLomaLlc label edlL, column re-order, hoL-Lracklng, Lhe
four maln modes LhaL you see ln explorer:
1. Icon - ulsplays lLems wlLh large lcons and your maln LexL
2. Sma|| Icon - ulsplays lLems wlLh small lcons and your maln LexL
3. L|st - ulsplays lLems wlLh your maln LexL
4. Deta|| - ulsplays lLems wlLh small lcons, your maln LexL, and any oLher daLa Lo be dlsplayed ln
columns.
Adding Multiple Columns

Now I add five columns to the control. You can add column headers to the control using its
Columns.Add method. The Columns.Add method takes column header name, its width, and
alignment.

In our sample, I write code at Form_Load method to do so.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
' Adding ListView Columns
ListView1.Columns.Add("Emp Name", 100, HorizontalAlignment.Left)
ListView1.Columns.Add("Emp Address", 150,
HorizontalAlignment.Left)ListView1.Columns.Add("Title", 60,
HorizontalAlignment.Left)
ListView1.Columns.Add("Salary", 50,
HorizontalAlignment.Left)ListView1.Columns.Add("Department", 60,
HorizontalAlignment.Left)
End Sub

Listing 1. Adding Column Headers of a ListView Control
After adding this code, the output of program looks like Figure 2.




----------------------------------------------------------------------------------------------------------------------------------------------
60
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Add, Remove and Clear Items Form ListView Control
ListView control allows you to display item text in a list. For example you are selecting files from a TreeView
control using ListView control you can display all your selected files in a list. Using ListViewItem class you can
access list of items present in a List. Each item that is added in a list forms a collection named as
ListViewItemCollection. Here I will use three of its methods Items.Add, Item.Remove and
Items.Clear.

To begin with this application adds four controls on your windows form (dialog box) and that are; Label
Control, TextBox Control, ListView Control and finally three Button Controls named as cmdAddItem_Click,
cmdRemoveItem_Click and cmdClear_Click. Code for these three events are as follows:

Private Sub cmdAddItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdAddItem.Click

lvItemList.Items.Add(txtAddItem.Text & "")

End Sub


Private Sub cmdRemoveItem_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdRemoveItem.Click

For Each lvItem As ListViewItem In lvItemList.SelectedItems
lvItem.Remove()
Next

End Sub

Private Sub cmdClear_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdClear.Click

lvItemList.Items.Clear()

End Sub


----------------------------------------------------------------------------------------------------------------------------------------------
61
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
rogress8ar

A rogress8ar conLrol ls used Lo represenL Lhe progress of a lengLhy operaLlon LhaL Lakes Llme where a user
has Lo walL for Lhe operaLlon Lo be flnlshed.
Creat|ng a rogress8ar


We can creaLe a rogress8ar conLrol uslng a lorms deslgner aL deslgn-Llme or uslng Lhe rogress8ar
class ln code aL run-Llme.
Des|gn-t|me


1o creaLe a rogress8ar conLrol aL deslgn-Llme, you slmply drag and drop a rogress8ar conLrol
from 1oolbox Lo a lorm ln vlsual SLudlo. AfLer you drag and drop a rogress8ar on a lorm, Lhe
rogress8ar1 ls added Lo Lhe lorm and looks llke llgure 1.




kun-t|me
CreaLlng a rogress8ar conLrol aL run-Llme ls merely a work of creaLlng an lnsLance of rogress8ar
class, seL lLs properLles and adds rogress8ar class Lo Lhe lorm conLrols.
llrsL sLep Lo creaLe a dynamlc rogress8ar ls Lo creaLe an lnsLance of rogress8ar class. 1he
followlng code snlppeL creaLes a rogress8ar conLrol ob[ecL.
Dim pBar As New ProgressBar()

ln Lhe nexL sLep, you may seL properLles of a rogress8ar conLrol. 1he followlng code snlppeL seLs LocaLlon,
name, WldLh, and PelghL properLles of a rogress8ar.
pBar.Location = New System.Drawing.Point(20, 20)
pBar.Name = "progressBar1"
pBar.Width = 200
pBar.Height = 30
me.Controls.Add(pBar)

-----------------------------------------------------------------------------------------------------------------------------
Sett|ng rogress8ar ropert|es
AfLer you place a rogress8ar conLrol on a lorm, Lhe nexL sLep ls Lo seL properLles.
1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
rlghL cllck on a conLrol and selecL roperLles menu lLem
Name


name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.

PBar.Name = "ProgresBar1"
os|t|on|ng a rogress8ar
We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
properLy.
. A ltoqtess8ot coo ooly be posltlooeJ botlzootolly.
1he uock properLy ls used Lo seL Lhe poslLlon of a rogress8ar. lL ls of Lype uockSLyle L
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and
PelghL properLles of a rogress8ar conLrol.

PBar.Dock = DockStyle.Bottom
M|n|mum, Max|mum, and Va|ue
-----------------------------------------------------------------------------------------------------------------------------
Sett|ng rogress8ar ropert|es
AfLer you place a rogress8ar conLrol on a lorm, Lhe nexL sLep ls Lo seL properLles.
1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
rlghL cllck on a conLrol and selecL roperLles menu lLem
name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.
PBar.Name = "ProgresBar1"
os|t|on|ng a rogress8ar
We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
properLy.
. A ltoqtess8ot coo ooly be posltlooeJ botlzootolly.
1he uock properLy ls used Lo seL Lhe poslLlon of a rogress8ar. lL ls of Lype uockSLyle L
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and
PelghL properLles of a rogress8ar conLrol.
PBar.Dock = DockStyle.Bottom
M|n|mum, Max|mum, and Va|ue

-----------------------------------------------------------------------------------------------------------------------------
Sett|ng rogress8ar ropert|es
AfLer you place a rogress8ar conLrol on a lorm, Lhe nexL sLep ls Lo seL properLles.
1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
rlghL cllck on a conLrol and selecL roperLles menu lLem
name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.
PBar.Name = "ProgresBar1"
os|t|on|ng a rogress8ar


We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
. A ltoqtess8ot coo ooly be posltlooeJ botlzootolly.
1he uock properLy ls used Lo seL Lhe poslLlon of a rogress8ar. lL ls of Lype uockSLyle L
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and
PelghL properLles of a rogress8ar conLrol.
PBar.Dock = DockStyle.Bottom
M|n|mum, Max|mum, and Va|ue
-----------------------------------------------------------------------------------------------------------------------------
Sett|ng rogress8ar ropert|es


AfLer you place a rogress8ar conLrol on a lorm, Lhe nexL sLep ls Lo seL properLles.
1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
rlghL cllck on a conLrol and selecL roperLles menu lLem
name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.
PBar.Name = "ProgresBar1"
We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
. A ltoqtess8ot coo ooly be posltlooeJ botlzootolly.
1he uock properLy ls used Lo seL Lhe poslLlon of a rogress8ar. lL ls of Lype uockSLyle L
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and
PelghL properLles of a rogress8ar conLrol.
PBar.Dock = DockStyle.Bottom
M|n|mum, Max|mum, and Va|ue


-----------------------------------------------------------------------------------------------------------------------------
AfLer you place a rogress8ar conLrol on a lorm, Lhe nexL sLep ls Lo seL properLles.
1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
rlghL cllck on a conLrol and selecL roperLles menu lLem. 1he roperLles wlndow looks llke llgure 2.
llqote 2


name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.
We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
. A ltoqtess8ot coo ooly be posltlooeJ botlzootolly.
1he uock properLy ls used Lo seL Lhe poslLlon of a rogress8ar. lL ls of Lype uockSLyle L
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and


-----------------------------------------------------------------------------------------------------------------------------
AfLer you place a rogress8ar conLrol on a lorm, Lhe nexL sLep ls Lo seL properLles.
1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
. 1he roperLles wlndow looks llke llgure 2.

name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.
We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
. A ltoqtess8ot coo ooly be posltlooeJ botlzootolly.
1he uock properLy ls used Lo seL Lhe poslLlon of a rogress8ar. lL ls of Lype uockSLyle L
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and
-----------------------------------------------------------------------------------------------------------------------------
AfLer you place a rogress8ar conLrol on a lorm, Lhe nexL sLep ls Lo seL properLles.

1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
. 1he roperLles wlndow looks llke llgure 2.

name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.
We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
1he uock properLy ls used Lo seL Lhe poslLlon of a rogress8ar. lL ls of Lype uockSLyle L
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and
----------------------------------------------------------------------------------------------------------------------------------------------
1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
. 1he roperLles wlndow looks llke llgure 2.

name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.
We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
1he uock properLy ls used Lo seL Lhe poslLlon of a rogress8ar. lL ls of Lype uockSLyle LhaL can have
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and
-----------------
62
1he easlesL way Lo seL properLles ls from Lhe roperLles Wlndow. ?ou can open roperLles wlndow by presslng l4 or
name properLy represenLs a unlque name of a rogress8ar conLrol. lL ls used Lo access Lhe conLrol
ln Lhe code. 1he followlng code snlppeL seLs and geLs Lhe name and LexL of a rogress8ar conLrol.
We can use Lhe LocaLlon properLy Lo poslLlon a conLrol. We can also dock a conLrol uslng Lhe uock
haL can have
values 1op, 8oLLom, LefL, 8lghL, and llll. 1he followlng code snlppeL seLs LocaLlon, WldLh, and
-----------------------------------------------------------------------------------------------------------------------------
1he Mlnlmum and Maxlmum properLles defln
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value
properLy Lo show Lhe pro

PBar.Minimum = 0
PBar.Maximum = 100
PBar.Value = 70

A rogress8ar wlLh a value looks llke llgure 3.



-----------------------------------------------------------------------------------------------------------------------------
1he Mlnlmum and Maxlmum properLles defln
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value
properLy Lo show Lhe pro

PBar.Minimum = 0
PBar.Maximum = 100
PBar.Value = 70
A rogress8ar wlLh a value looks llke llgure 3.

-----------------------------------------------------------------------------------------------------------------------------
1he Mlnlmum and Maxlmum properLles defln
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value
properLy Lo show Lhe progress of an operaLlon.
PBar.Minimum = 0
PBar.Maximum = 100
PBar.Value = 70
A rogress8ar wlLh a value looks llke llgure 3.

-----------------------------------------------------------------------------------------------------------------------------
1he Mlnlmum and Maxlmum properLles defln
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value
gress of an operaLlon.
A rogress8ar wlLh a value looks llke llgure 3.
-----------------------------------------------------------------------------------------------------------------------------
1he Mlnlmum and Maxlmum properLles deflne Lhe range of a rogress8ar. 1he value properLy
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value
gress of an operaLlon.
A rogress8ar wlLh a value looks llke llgure 3.
-----------------------------------------------------------------------------------------------------------------------------
e Lhe range of a rogress8ar. 1he value properLy
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value
-----------------------------------------------------------------------------------------------------------------------------
e Lhe range of a rogress8ar. 1he value properLy
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value

----------------------------------------------------------------------------------------------------------------------------------------------
e Lhe range of a rogress8ar. 1he value properLy
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value
-----------------
63
e Lhe range of a rogress8ar. 1he value properLy
represenLs Lhe currenL value of a rogress8ar. 1he currenL value of Lhe rogress8ar from Lhe
mlnlmum value ls colored green shows Lhe progress of a conLrol. We can also use Lhe value

----------------------------------------------------------------------------------------------------------------------------------------------
64
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Delegates

A delegate is a type that references a method. Once a delegate is assigned a method, it
behaves exactly like that method. The delegate method can be used like any other method, with
parameters and a return value, as in this example:
Any method that matches the delegate's signature, which consists of the return type and
parameters, can be assigned to the delegate. This makes is possible to programmatically change
method calls, and also plug new code into existing classes. As long as you know the delegate's
signature, you can assign your own delegated method.
Delegates have the following properties:
Delegates are similar to C++ function pointers, but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single
event.
Let's first take a quick look at how to define and invoke a delegate. First we declare our delegate in
our form class:
Private Delegate Sub MyDelSub()
OR
Private Delegate Function MyDelegate(i As Integer, j As Integer) As Integer

De|egate Lxamp|e

Public Class Form1

Public Delegate Function MyDelegate(ByVal i As Integer, ByVal j As
Integer) As Integer

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

Dim myDel As New MyDelegate(AddressOf f1)
Dim res1 As Integer = myDel(10, 5)
MessageBox.Show(res1) ------- output= 15

Dim myDel As New MyDelegate(AddressOf f2)
Dim res2 As Integer = myDel(10, 5)
MessageBox.Show(res2) ------- output= 5

Dim myDel As New MyDelegate(AddressOf f3)
Dim res3 As Integer = myDel(10, 5)
MessageBox.Show(res3) ------- output= 50

End Sub



----------------------------------------------------------------------------------------------------------------------------------------------
63
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328


Public Function f1(ByVal i As Integer, ByVal j As Integer) As Integer
Return i + j
End Function

Public Function f2(ByVal i As Integer, ByVal j As Integer) As Integer
Return i - j
End Function

Public Function f3(ByVal i As Integer, ByVal j As Integer) As Integer
Return i * j
End Function
End Class


----------------------------------------------------------------------------------------------------------------------------------------------
66
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Events & delegate

Events are certain actions that happen during the execution of a program that the application
wishes to be notified about, so it can respond. An event can be a mouse click, a keystroke or the
coming of a certain time (alarm). An event is basically a message which is said to be fired or
triggered when the respective action occurs.
A class that raises an event is called an 'event sender', a class that receives an event is
called and 'event consumer' and a method which is used to handle a particular event is called an
'event handler'.
Events in the .NET Framework are based on the delegate model. Delegates are type-safe
Function Pointers or Callbacks.
Implementation of an event is a three-step procedure.
1. Declare a delegate, if definition is not provided the .Net Framework would provide a default
delegate implementation.
2. Declare the event signature using the Event keyword and Raise the event using the
RaiseEvent statement.
3. Handle the Event by declaring an event receiver, often called an event handler. Which is a
subroutine that responds to an event.
Lets now take each step on by one.
Declare a delegate.
A delegate is a class that can hold a reference to a method. A delegate class has a signature, and it
can hold references only to methods that match its signature. A delegate can be defined as
Delegate Sub sampleDel(Cancel as Boolean).

Any method that has same signature can be attached to this delegate; a procedure that would have
the same signature can handle this event.
Declare an Event and Raise It.
An even can be declared in mainly three ways.
evtSample As sampleDel-The mechanism to register the event handler, for this type of declaration
is to be provided by the class declaring the event. The event is implemented by using the explicitly
declared delegate.
The event is raised by making a call to evtSample.
Public Event evtSample as sampleDel-The event handler can be registered by using AddHandler
method in the Class that would provide a Handler. The event is implemented by using the above-
declared delegate.
The event is raised by making a call to RaiseEvent.

----------------------------------------------------------------------------------------------------------------------------------------------
67
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Public Event evtSample(Cancel as Boolean)-The event handler procedure would be registered by
using the Handles keyword in the declaration itself. The event is implemented by using implicitly
declared delegate by the framework.
The event is raised by making a call to RaiseEvent.
Handle the Event.
Declaring a sub and either attaching it to the delegate or registering with the event declaring class
can handle the event.





----------------------------------------------------------------------------------------------------------------------------------------------
68
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Files in VB .NET
Working with Files
File handling in Visual Basic is based on System.IO namespace with a class library that supports
string, character and file manipulation. These classes contain properties, methods and events for
creating, copying, moving, and deleting files. Since both strings and numeric data types are
supported, they also allow us to incorporate data types in files. The most commonly used classes
are FileStream, BinaryReader, BinaryWriter, StreamReader and StreamWriter.
FileStream Class
This class provides access to standard input and output files. We use the members of FileAccess,
FileMode and FileShare Enumerations with the constructors of this class to create or open a file.
After a file is opened it's FileStream object can be passed to the Binary Reader, BinaryWriter,
Streamreader and StreamWriter classes to work with the data in the file. We can also use the
FileStreamSeek method to move to various locations in a file which allows to break a file into
records each of the same length.
StreamReader and StreamWriter Class
The StreamReader and StreamWriter classes enables us to read or write a sequential stream of
characters to or from a file.
BinaryReader and BinaryWriter Class
The BinaryReader and BinaryWriter classes enable us to read and write binary data, raw 0's and
1's, the form in which data is stored on the computer.
The following examples puts some code to work with textual data using FileStream and
StreamReader and StreamWriter classes.

FileStream Class
This class provides access to standard input and output files. We use the members of FileAccess,
FileMode and FileShare Enumerations with the constructors of this class to create or open a file.
After a file is opened it's FileStream object can be passed to the Binary Reader, BinaryWriter,
Streamreader and StreamWriter classes to work with the data in the file.
The FileStream class opens a file either in synchronous or asynchronous mode.
Synchronous mode the entire file is first read and then displayed to the user. It is a default mode.
The methods used to open a file in synchronous mode are read() and write().
Asynchronous mode when file gets open in asynchronous mode, .NET application start reading
and displaying a file in parts, without waiting for the entire file to be read first and then displayed.
The methods are beginRead() and beginWrite().


----------------------------------------------------------------------------------------------------------------------------------------------
69
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
FileMode
Append - Open the file if it exists and seek to the end of the file, or create a new file.
Create - Create a new file. If file exists, it will be overwritten.
CreateNew - Create a new file. If file exists, throw an exception.
Open - Open an existing file.
OpenOrCreate - Open a file if it exists, otherwise create a new file
Truncate - Open an existing file, once opened the file should be truncated so that its size is zero. If
file does not exist, throw an exception.
This class provides access to standard input and output files.
||m ls ss ssw |||st.ssm (,st|. |||sMsis. |||s/sssss. |||s|s.s)
The following example shows , how to write in a file using FileStream.

Imports System.IO


Public Class Tester
Public Shared Sub Main
Dim w As StreamWriter
w = File.AppendText("test.txt")

w.Write("it is writing data")
w.WriteLine(1)
w.WriteLine("writeline")
w.WriteLine("True")
w.Close()
End Sub

End Class


----------------------------------------------------------------------------------------------------------------------------------------------
70
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Directory operations
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.
ex : 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.
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(sourceulrname,desLulrname)
ex : 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
ex : Directory.Delete("c:\testdir1")
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 Directory.Exists("c:\testDir1") Then
'shows message if testdir1 exist
MsgBox("Directory 'testDir' Exist ")
Else
'create the directory testDir1
Directory.CreateDirectory("c:\testDir1")
MsgBox("testDir1 created ! ")
'create the directory testDir2

Directory.CreateDirectory("c:\testDir1\testDir2")
MsgBox("testDir2 created ! ")
'move the directory testDir2 as testDir in c:
Directory.Move("c:\testDir1\testDir2", "c:\testDir")
MsgBox("testDir2 moved ")
'delete the directory testDir1
Directory.Delete("c:\testDir1")
MsgBox("testDir1 deleted ")
End If
End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
71
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Files operations
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.
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.
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.
Copy(sourceFileName, destFileName)
ex : 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)
VB.NET : File.Delete("c:\testDir\testFile.txt")

----------------------------------------------------------------------------------------------------------------------------------------------
72
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
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 Not File.Exists("c:\testFile.txt") Then
MsgBox("FIle not exist ")
Else
File.Copy("c:\testFile.txt",
"c:\testDir\testFile.txt")
MsgBox("File Copied ")
File.Delete("c:\testFile.txt")
MsgBox("file deleted ")
End If
End Sub
End Class


----------------------------------------------------------------------------------------------------------------------------------------------
73
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
BinaryReader and BinaryWriter
A sLreamlng operaLlon ls Lyplcally used Lo creaLe a sLream. Cnce Lhe sLream ls ready, you can
wrlLe daLa Lo lL. 1he wrlLlng operaLlon ls performed Lhrough varlous classes. Cne of Lhese classes ls
8lnaryWrlLer.
1he 8lnary8eader and 8lnaryWrlLer classes enable us Lo read and wrlLe blnary daLa, raw 0's
and 1's, Lhe form ln whlch daLa ls sLored on Lhe compuLer.
1he 8lnaryWrlLer class can be used Lo wrlLe values of prlmlLlve daLa Lypes (char, lnL, floaL,
double, eLc). 1o use a 8lnaryWrlLer value, you can flrsL declare lLs polnLer.
Cnce Lhe sLream ls ready, you can geL prepared Lo read daLa from lL. 1o supporL Lhls, you can
use Lhe 8lnary8eader class.
AfLer uslng Lhe sLream, you should close lL Lo reclalm Lhe resources lL was uslng. 1hls ls done
by calllng Lhe Close() meLhod.



Sub Main()
'save 10 double values to the file.
Try
Dim fs As FileStream
fs = New FileStream ("c:\binaryfile.txt",
FileMode.OpenOrCreate)
Dim i As Integer
Dim rand As New Random
Dim bw As New BinaryWriter (fs)
Dim br As New BinaryReader (fs)
' writting to the file
For i = 0 To 10
bw.Write (rand.NextDouble)
Next
'reading from a file
br.BaseStream.Seek(0, SeekOrigin.Begin)
Do Until br.PeekChar = -1
Console.WriteLine (br.ReadDouble)
Loop
bw.Close()
br.Close()
fs.Close()
Catch ex As Exception
Console.WriteLine (ex.Message)
End Try
Console.ReadLine()
End Sub


----------------------------------------------------------------------------------------------------------------------------------------------
74
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
StreamReader and StreamWriter
1he SLream8eader and SLreamWrlLer classes enables us Lo read or wrlLe a sequenLlal sLream
of characLers Lo or from a flle. As menLloned earller, Lhe lLems Lo save on a documenL are prlmarlly
consldered as blLs. 1hls makes lL posslble Lo save small pleces of lnformaLlon such as Lhose LhaL
would flL a byLe, a char, a shorL, or a double value. 1o supporL Lhe ablllLy Lo wrlLe one characLer, Lhe
SysLem.lC namespace provldes Lhe 1exLWrlLer class. 1hls class ls absLracL, meanlng you can'L
lnsLanLlaLe an ob[ecL of lL. lnsLead, you can use one of lLs derlved classes, parLlcularly Lhe
SLreamWrlLer class.
1o read daLa from a sLream, you can use Lhe SLream8eader class, whlch ls derlved from Lhe
1exL8eader class. 1o read a characLer from a sLream, use 8ead() meLhod.






Imports System.IO

Dim path As String = "c:\temp\MyTest.txt"

Try

Dim sr As StreamReader = New StreamReader(path)

'This allows you to do one Read operation.
RichTextBox1.Text = sr.ReadToEnd()
sr.Close()

Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())

End Try

----------------------------------------------------------------------------------------------------------------------------------------------
73
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
ADO.NET

ADO.NET Architecture

ADO.NET is an object-oriented set of libraries that allows you to interact with data sources.
Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or
an XML file.
ADO.NET is a part of the .NET Framework
ADO.NET consists of a set of classes used to handle data access
The ADO.NET Framework supports two models of Data Access Architecture, Connection
Oriented Data Access Architecture and Disconnected Data Access Architecture.
In Connection Oriented Data Access Architecture the application makes a connection to the
Data Source and then interact with it through SQL requests using the same connection. In these
cases the application stays connected to the database system even when it is not using any
Database Operations.
ADO.Net solves this problem by introduces a new component called Dataset. The DataSet
is the central component in the ADO.NET Disconnected Data Access Architecture. A DataSet is an
in-memory data store that can hold multiple tables at the same time. DataSets only hold data and
do not interact with a Data Source. One of the key characteristics of the DataSet is that it has no
knowledge of the underlying Data Source that might have been used to populate it.
Data Access in ADO.NET relies on two components: DataSet and Data Provider.

DataSet
The dataset is a disconnected, in-memory representation of data. It can be considered as a
local copy of the relevant portions of the database. The DataSet is persisted in memory and the
data in it can be manipulated and updated independent of the database. When the use of this
DataSet is finished, changes can be made back to the central database for updating. The data in
DataSet can be loaded from any valid data source like Microsoft SQL server database, an Oracle
database or from a Microsoft Access database.

Data Provider
The Data Provider is responsible for providing and maintaining the connection to the
database. A DataProvider is a set of related components that work together to provide data in an
efficient and performance driven manner. The .NET Framework currently comes with two
DataProviders: the SQL Data Provider which is designed only to work with Microsoft's SQL Server
7.0 or later and the OleDb DataProvider which allows us to connect to other types of databases like
Access and Oracle. Each DataProvider consists of the following component classes:
-----------------------------------------------------------------------------------------------------------------------------
The
The
The
The
update

Data access with ADO.NET can be s
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
more than a single value, the command object
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
using the command object or the DataAdapter.
ADO.NET architecture

Component classes that make up the Data
The Connection Object
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
to connect to Microsoft SQL Server
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database.
Setting the Connection
Dim strCon
database=

Dim con
-----------------------------------------------------------------------------------------------------------------------------
The Connection
The Command
The DataReader
The DataAdapter
Data access with ADO.NET can be s
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
more than a single value, the command object
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
using the command object or the DataAdapter.
ADO.NET architecture
Component classes that make up the Data
The Connection Object
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
to connect to Microsoft SQL Server
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database.
Setting the Connection
strCon As String = Data Source=
database=db_name
con As Sqlconnection = New SqlConnection(

-----------------------------------------------------------------------------------------------------------------------------
Connection object which provides a connection to the database
object which is used to execute a command
DataReader object which provides a forward
DataAdapter object which populates a disconnected DataSet with data and performs
Data access with ADO.NET can be s
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
more than a single value, the command object
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
using the command object or the DataAdapter.
ADO.NET architecture
Component classes that make up the Data
The Connection Object
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
to connect to Microsoft SQL Server
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database.
Setting the Connection String property
As String = Data Source=

As Sqlconnection = New SqlConnection(
-----------------------------------------------------------------------------------------------------------------------------
object which provides a connection to the database
object which is used to execute a command
object which provides a forward
object which populates a disconnected DataSet with data and performs
Data access with ADO.NET can be s
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
more than a single value, the command object
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
using the command object or the DataAdapter.
Component classes that make up the Data
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
to connect to Microsoft SQL Server, and the OleDbConnection object, which can provide
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database.
String property:
As String = Data Source=
As Sqlconnection = New SqlConnection(
-----------------------------------------------------------------------------------------------------------------------------
object which provides a connection to the database
object which is used to execute a command
object which provides a forward-only, read only, connected recordset
object which populates a disconnected DataSet with data and performs
Data access with ADO.NET can be summarized as follows:
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
more than a single value, the command object returns a DataReader to provide the data.
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
using the command object or the DataAdapter.
Component classes that make up the Data Providers
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
, and the OleDbConnection object, which can provide
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database.

As String = Data Source=server_name
As Sqlconnection = New SqlConnection(
-----------------------------------------------------------------------------------------------------------------------------
object which provides a connection to the database
object which is used to execute a command
only, read only, connected recordset
object which populates a disconnected DataSet with data and performs
ummarized as follows:
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
returns a DataReader to provide the data.
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
Providers
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
, and the OleDbConnection object, which can provide
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database.
_name; integrated security=SSPI;
As Sqlconnection = New SqlConnection(strCon)
-----------------------------------------------------------------------------------------------------------------------------
object which provides a connection to the database
only, read only, connected recordset
object which populates a disconnected DataSet with data and performs
ummarized as follows:
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
returns a DataReader to provide the data.
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
, and the OleDbConnection object, which can provide
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database.
; integrated security=SSPI;
)
----------------------------------------------------------------------------------------------------------------------------------------------
only, read only, connected recordset
object which populates a disconnected DataSet with data and performs

A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
returns a DataReader to provide the data.
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated

The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
, and the OleDbConnection object, which can provide
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
object contains all of the information required to open a connection to the database.
; integrated security=SSPI;
-----------------
76
only, read only, connected recordset
object which populates a disconnected DataSet with data and performs
A connection object establishes the connection for the application with the database. The
command object provides direct execution of the command to the database. If the command returns
Alternatively, the DataAdapter can be used to fill the Dataset object. The database can be updated
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed specifically
connections to a wide range of database types like Microsoft Access and Oracle. The Connection
; integrated security=SSPI;

----------------------------------------------------------------------------------------------------------------------------------------------
77
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
The Command Object
The Command object is represented by two corresponding classes: SqlCommand and
OleDbCommand. Command objects are used to execute commands to a database across a data
connection. The Command objects can be used to execute stored procedures on the database,
SQL commands, or return complete tables directly. Command objects provide three methods that
are used to execute commands on the database:
ExecuteNonQuery: Executes commands that have no return values such as INSERT,
UPDATE or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object

The DataReader Object
The DataReader object provides a forward-only, read-only, connected stream recordset from a
database. Unlike other components of the Data Provider, DataReader objects cannot be directly
instantiated. Rather, the DataReader is returned as the result of the Command object's
ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader
object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object. The
DataReader can provide rows of data directly to application logic when you do not need to keep the
data cached in memory. Because only one row is in memory at a time, the DataReader provides the
lowest overhead in terms of system performance but requires the exclusive use of an open
Connection object for the lifetime of the DataReader.

The DataAdapter Object
The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is
essentially the middleman facilitating all communication between the database and a DataSet. The
DataAdapter is used either to fill a DataTable or DataSet with data from the database with it's Fill
method. After the memory-resident data has been manipulated, the DataAdapter can commit the
changes to the database by calling the Update method. The DataAdapter provides four properties
that represent database commands:
SelectCommand
InsertCommand
DeleteCommand
UpdateCommand
When the Update method is called, changes in the DataSet are copied back to the database
and the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed.



----------------------------------------------------------------------------------------------------------------------------------------------
78
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Connection to database with server explorer
To connect to a database from Server Explorer
1. lrom Lhe V|ew menu, choose Server Lxplorer.
2. ln Server Lxplorer rlghL-cllck Lhe Data Connect|ons node and choose Add Connect|on.
3. lf Lhls ls Lhe flrsL connecLlon you make, Lhe Choose Data Source dlalog box appears. ln Lhls
dlalog box under Data Source choose Lhe klnd of daLa source Lo whlch you are connecLlng,
and Lhen under Data rov|der choose Lhe provlder approprlaLe for Lhe appllcaLlon you are
worklng wlLh. llnally cllck Cont|nue.
4. ln Lhe Add Connect|on dlalog box enLer Lhe requesLed lnformaLlon.
1hls lnformaLlon ls dlfferenL for each provlder. lor more he|p on Lhls Lab, cllck Lhe Pelp lcon
aL Lhe Lop of Lhe dlalog box or press l1 wlLh Lhe dlalog box selecLed.
3. Cllck Lhe Advanced buLLon Lo brlng up a llsL of properLles where you can change seLLlngs for
Lhe selecLed provlder.
6. Cllck 1est Connect|on Lo check Lhe connecLlon wlLhouL closlng Lhe dlalog box. 1hls way you
can make ad[usLmenLs Lo Lhe seLLlngs lf Lhe connecLlon does noL succeed.
7. Cllck Ck.
?our connecLlon appears ln Server Lxplorer under Lhe Data Connect|ons node.


To create a data connection to a SQL Server database
1. ln Lhe Choose Data Source dlalog box, selecL M|crosoft SL Server, and Lhen cllck Ck.
lf Lhe Add Connect|on dlalog box opens, and Lhe Data source ls noL M|crosoft SL Server,
cllck Change Lo open Lhe Choose]Change Data Source dlalog box. lor more lnformaLlon, see
Choose/Change uaLa Source ulalog 8ox.
2. SelecL a server name from Lhe drop-down llsL, or Lype Lhe name of Lhe server where Lhe
daLabase you wanL Lo access ls locaLed.
3. 8ased on Lhe requlremenLs of your daLabase or appllcaLlon, selecL elLher W|ndows
Authent|cat|on or use a speclflc user name and password Lo log on Lo Lhe SCL Server (SL
Server Authent|cat|on). lor more lnformaLlon, see Add/Modlfy ConnecLlon (MlcrosofL SCL
Server).
4. SelecL Lhe daLabase you wanL Lo connecL Lo from Lhe drop-down llsL.
3. Cllck Ck.



----------------------------------------------------------------------------------------------------------------------------------------------
79
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Create Connection String:
1) With SqlServer:









2) With MS Access:

Imports System.Data.SqlClient

Public Class Form2

Dim con As New SqlConnection()

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load

con.ConnectionString = "Data source=server_name; initial
catalog=DB_name; integrated security=SSPI"

con.Open()

End Sub
End Class
Imports System.Data. OleDb

Public Class Form2

Dim con As New OleDbConnection()

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load

con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\mydatabase.mdb"

con.Open()

End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
80
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Insert Data:














Imports System.Data.SqlClient

Public Class Form2

Dim con As New SqlConnection()
Dim cmd As New SqlCommand()

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data source=server_name; initial
catalog=DB_name; integrated security=SSPI"
con.Open()

cmd.Connection = con
cmd.CommandText = "insert into emp values (101, 'some
text', 'some text' )"
cmd.ExecuteNonQuery()

con.Close()

End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
81
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Insert Data (values from user):

















Imports System.Data.SqlClient

Public Class Form2

Dim con As New SqlConnection()
Dim cmd As New SqlCommand()

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data source=server_name; initial
catalog=DB_name; integrated security=SSPI"
con.Open()

cmd.Connection = con
cmd.CommandText = "insert into emp values (" &
TextBox1.Text & ", '" & TextBox2.Text & "', '" &
TextBox3.Text & "' )"
cmd.ExecuteNonQuery()

con.Close()

End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
82
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Update Table (values from user):
















Imports System.Data.SqlClient

Public Class Form2

Dim con As New SqlConnection()
Dim cmd As New SqlCommand()

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data source=server_name; initial
catalog=DB_name; integrated security=SSPI"
con.Open()

cmd.Connection = con
cmd.CommandText = "update emp set emp_name=" &
TextBox2.Text & ", emp_address=" & TextBox3.Text & "
where emp_id= " & TextBox1.Text
cmd.ExecuteNonQuery()

con.Close()

End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
83
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Binding Data to TextBox:


















Imports System.Data.SqlClient

Public Class Form2

Dim con As New SqlConnection("Integrated
Security=SSPI;Persist Security Info=False;Initial
Catalog=aims;Data Source=VISION")
Dim cmd As New SqlCommand()
Dim dr As SqlDataReader

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

con.Open()

cmd.Connection = con
cmd.CommandText = "Select * from mca"
dr = cmd.ExecuteReader()

If dr.Read() = True Then
TextBox1.Text = dr(0).ToString()
TextBox2.Text = dr(1).ToString()
TextBox3.Text = dr(2).ToString()
End If

End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
84
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Binding Data to ListBox:


















Imports System.Data.SqlClient

Public Class Form2

Dim con As New SqlConnection("Integrated
Security=SSPI;Persist Security Info=False;Initial
Catalog=aims;Data Source=VISION")
Dim cmd As New SqlCommand()
Dim dr As SqlDataReader

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

con.Open()

cmd.Connection = con
cmd.CommandText = "Select * from mca"
dr = cmd.ExecuteReader()

While dr.Read() = True

ListBox1.Items.Add(dr(0).ToString())

End While

End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
83
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Binding Data to Data grid:














Imports System.Data.SqlClient

Public Class Form2

Dim con As New SqlConnection("Integrated
Security=SSPI;Persist Security Info=False;Initial
Catalog=aims;Data Source=VISION")
Dim ds As New DataSet()
Dim adp As SqlDataAdapter

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

adp = New SqlDataAdapter("Select * from mca", con)
adp.Fill(ds)

DataGridView1.DataSource = ds.Tables(0)

End Sub
End Class

----------------------------------------------------------------------------------------------------------------------------------------------
86
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Crystal Reports
Crystal Reports is the standard reporting tool for Visual Studio .NET used to display data of
presentation quality. You can display multiple-level totals, charts to analyze data, and much more in
Crystal Reports. Creating a Crystal Report requires minimal coding since it is created in Designer
interface. It is available as an integrated feature of Microsoft Visual Studio .NET,

Advantages of Crystal Reports
Some of the major advantages of using Crystal Reports are:
1. Rapid report development since the designer interface would ease the coding work for the
programmer.
2. Can extend it to complicated reports with interactive charts and enhance the understanding of the
business model
3. Exposes a report object model, can interact with other controls on the ASP.NET Web form
4. Can programmatically export the reports into widely used formats like .pdf, .doc, .xls, .html and
.rtf



----------------------------------------------------------------------------------------------------------------------------------------------
87
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Creating a Crystal Report Project
It is relatively easy to retrieve data from a database and display it using any of the bound
controls. This is especially so in ASP.NET 2.0 where the amount of code you need to write has been
drastically reduced. However, to present the data in a formal, board-room friendly format and
distribute it in hard copy, or for look-up, or both is challenging. Crystal Reports does this remarkably
well. Microsoft has been bundling Crystal reports ever since the VB days, and it ships with every
version of VS 2005. It is well integrated with Visual Studio 2005 as we shall see shortly. For highly
functional and aesthetically pleasing report generation, Crystal Report is ideally suited. It is very
versatile and can use data from a variety of databases as well as non-traditional sources.
Crystal Report comes with its own SDK which can be used to programmatically create reports and
interact with them at run time, if one desires do so. Crystal Reports can be us in either Windows or a
web application. It can be stand alone or made available over the Internet. These reports can be
utilized in many different ways: application embedded reports; reports from web servers; as web
services; and so forth. In VS 2005 you find two Crystal Report objects, the CrystalReportViewer and
the ReportDocument as shown in the next picture.

The Object Browser reveals the various classes that are integrated with the Visual Studio application
as shown in the next picture.

Create a new project, accessing it from the File menu. This opens the New Project window listing
Business Intelligence Projects at the top as shown. In the Visual Studio Installed templates area,
highlight Crystal Reports Application. The default has been changed to Diamond in the Name: field
as shown. This application will have a Windows interface for a Crystal Report.

----------------------------------------------------------------------------------------------------------------------------------------------
88
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328


Project Folder Contents
The next picture shows the folder created by this application. It has a form, Form1.vb, and a yet to be
completed CrystalReport1.rpt. This is just a template of a report; when the wizard completes the
tasks, it will be filled with all the necessary information.


Report Generation
Invoking the Report Wizard
When the application is created, the CrystalReport1.rpt tab will be in the default view with the
window Crystal Reports Gallery contained in it as shown. As you can see from this you have three
options to choose from. For this tutorial, the first option is chosen.


----------------------------------------------------------------------------------------------------------------------------------------------
89
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Accessing the Data
When you click on the OK button, you will get to the Standard Report Creation Wizard window as
shown. There are lots of locations and sources that the data can come from, including the possibility
to create a new connection.

----------------------------------------------------------------------------------------------------------------------------------------------
90
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Creating a New Connection
For this tutorial a new connection will be established to get the data. When you expand the Create
New Connection node you will see even more options.

Choosing an OLEDB Provider
We will be using an OLEDB provider, so click on the OLEDB (ADO) folder which shows the
OLEDB Providers available in the drop-down in the right pane. We plan to get the data from the
SQL 2005 Server using the SQL Native Client. Highlight the SQL Native Client. Place a check mark
in the checkbox Use DataLink file. Well, you might not have a DataLink file ready to be used.
However, in the next sub-section we will create a DataLink file, and when this is created, we will
browse to it by clicking the ellipsis button (...) in the Ole DB Provider screen.

----------------------------------------------------------------------------------------------------------------------------------------------
91
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328


Creating a DataLink file
The Microsoft DataLink utility can be used to create a DataLink file with the *.udl extension. If you
create a new text document and change its extension from *.txt to *udl, a DataLink file will be
created. This can be configured by double clicking the icon of the file. This opens the DataLink
Properties window as shown with the Connection tab in the default view. Click on the Provider tab,
and then scroll up or down until you locate the SQL Native Client. Highlight the SQL Native Client
and click Next, or change to the Connection tab.



----------------------------------------------------------------------------------------------------------------------------------------------
92
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
The data source is the SQL 2005 Server which in this case is Hodentek/Mysorian where Hodentek
is the Windows XP machine and Mysorian is the SQL 2005 Server instance. The logon information
is what is appropriate for the SA user. You may save the password with the connection. If the
information up to this point is correct, you will be able to access all the databases on this server as
shown in the drop-down box. For this report the Northwind database will be used. The reader will
benefit from the earlier SQL 2005 articles on the ASPFree.com site. At this point you can also verify
that the connection is correct by clicking the test button.

Make sure that after this task you go back to the OleDB Provider screen and browse and locate this
file.
Connecting to the Data Server
After locating the file, click on the Finish button. This brings up the next screen where you make the
connection by providing the authentication information.


----------------------------------------------------------------------------------------------------------------------------------------------
93
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Do you want to change something?
When you click on the Next button, the OLEDB(AD0) screen presents some advanced information.
You could "Edit" or "Remove the Property" altogether. For this tutorial the default is accepted.

Selecting the Data
When you click on the Finish button in the above screen, you enter the next step of the report
creation wizard. You will be choosing the source of the data on the server you logged on. Here the
Northwind database will be used. You may access any of the objects; that includes some of the
system objects as well.


----------------------------------------------------------------------------------------------------------------------------------------------
94
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Selecting a table(s) from the database
We will be using one of the tables on this database, in particular, the Employees table. Expand the
Table node, highlight the Employees table, and click on the button marked ">". This will take the
Employees table to the Selected Tables: area as shown. Instead of a single table, multiple tables can
also be used.

Selecting Columns (Fields) from the table
A table can have a large number of columns, also called Fields. In a report, depending on the
requirement, one may or may not need all the columns. In this case, out of all the available fields
only a subset is chosen to be displayed. Transfer all these fields to be displayed from left pane to
right pane by clicking one-by-one, or highlighting them as a bunch and using the ">" button. By
using the Up/Down arrows in the Fields to Display pane, they can be reordered top to bottom.


----------------------------------------------------------------------------------------------------------------------------------------------
93
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Grouping the data
When you click on the Next button, you will be taken to the Grouping area. The Employees may
come from different cities and in this case they can be grouped on the basis of the city they come
from. In this screen you would choose the Employees. City and click on the ">" button to transfer it
to the Group By: column. In the background, the wizard is creating an appropriate SQL Select
statement.

Summarizing the data
When you click on the Next button, you will bring up the window shown where you may summarize
the data. The data fields we have chosen do not require summarizing, therefore you go the next task
by clicking the Next button on the following screen.


----------------------------------------------------------------------------------------------------------------------------------------------
96
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Selecting only required fields
Although this section is optional you may still want to make a change to the record selection. For
example FirstName was not chosen in the initial selection, but here it was added.


Choosing a Style for the Report
When you click on the Finish button in the above screen you will have completed all the tasks
related to data to be displayed. In this step you will choose the style from an available list of styles.
Here the last in the list, Maroon/Teal box, is chosen.


----------------------------------------------------------------------------------------------------------------------------------------------
97
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328
Design View of generated report
When you click Finish you will have created the report. At this point you will see two new windows,
which are described here. These two windows show the various report fields in a node tree, and the
design pane of the report.
Accessing various report fields
The Fields Explorer window shows all the different fields. This is the same as the ones you would
find in the earlier versions of Crystal Report, such as Crystal Report 8.5. In a more elaborate and
complex report you may need a combination of all of these fields.

Design pane of the report
The design pane of the report is also similar to the ones you would find in the earlier Crystal Report
versions, such as 8.5. This is the well know banded report with header, footer, and data-related
sections. You could drag and drop fields from the Field Explorer onto these sections if you were to
design a report from scratch.


Displaying the Report
Providing authentication
In order to display the report, when you build and run the project, you will have to provide the
authentication information which will be presented to you. The Main Report will be embedded
in Form1, and will be revealed when you are properly authenticated.

----------------------------------------------------------------------------------------------------------------------------------------------
98
2064, !aan Mohammed sLreeL, 8ehlnd Curesh Mas[ld, Camp une. h. 020-30462936, 9766118328

Displayed Report
After you click the Finish button, the report displays as shown in the next picture. On the left pane
you see the Grouping, in this case the various cities the employees come from, and on the right you
see the related personal information of the employee.

From the above window's main menu at the top, you can export the report; print the report; refresh
the report; toggle the Group tree; search for text; zoom up and down; and navigate the report.

Você também pode gostar