0% found this document useful (0 votes)
68 views142 pages

CSharp 2008

Csharp study notes

Uploaded by

Nilofer Varis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views142 pages

CSharp 2008

Csharp study notes

Uploaded by

Nilofer Varis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 142

Contents

1. Introducing Visual Studio 2008


2. Type of Application Architectures
3. Different type of architectures
. The .!"T Initiati#e
$. The .!"T %ra&e'or(
). The .!"T %ra&e'or( *ase Classes or The .!"T class %ra&e'or(
Namespace
Assemblies
The Common Language Runtime
Managed Code execution Process
+. %eatures ,ro#ided -y the C./
8. Ad#antages of the .!"T %ra&e'or(
0. Visual Studio 2008 ID"
10. Visual -asic 2008
11. Introduction To Varia-les1 Constants And Data Types.
Declaring variables
Scope of variables
12. 2perators 3sed In C4.!"T
13. Code 5odules In C4.!"T
1. To i&port pre6defined li-raries
1$. Console Applications
1). C2!V"/T class li-rary
1+. An Introduction to procedures
Sub procedure
unction procedure
Propert! procedure
18. Control Structures
Decision Statements
Looping Statements
10. The A//A7S
T!pe of arra!s
Arra! "nitiali#ation
Arra! Sorting
1
Arra! Reversing
D!namic Arra!s
20. "nu&eration Type
21. ST3/CT3/" in C4.!"T
Define Structure
ARRA$ %f Structure
Structure &ith properties
22. 2-8ect 2riented ,rogra&&ing in C4.!"T
Class
%b'ect
"nheritance
Constructors ( destructors
%verloading
%verriding
Structured exception handling
Multithreading
23. Defining a Class
2. Constructors and Destructors
2$. !a&e Spaces
2). To Define Class .i-rary
2+. Inheritance
28. Interfaces in C4.!"T
20. Structured "9ception handling
30. The Delegates
31. I:2 %ile 5anage&ent
)inar!Reader and )inar!*riter Classes
The StreamReader and Stream*riter
To handle files +sing C,-N.T Run/time unctions
32. The Directory class
33. 5ultithreading in C4.!"T
3. Co&&only used general .i-raray %unctions
3$. Creating ;indo's %or&s
3). ;indo's Controls
3+. 3sing <eneral &odules =5odule sheet>
38. ;indo's Co&&on dialog controls
30. Data-ase Connections in C4.!"T
The AD%-N.T
%leD)Connections
2
S0lConnections
%D)C Connections
0. 3sing DataAdapter and DataS"T
1. %iltering and Sorting Data
2. S?.Connection =using 5S6S?. Ser#er>
3. Creating /eports
. SDI and 5DI Applications
45. .I!?@ (Language-"Ntegrated 1uery)
). Deploying 7our Application
22////////////////////////////33
3
I!T/2D3CI!< VIS3A. ST3DI2 2008
Visual Studio is a complete set of development tools for building S!."#$ %eb
applications& '() %eb Services& des*top applications& and mobile applications. Visual
+asic& Visual ,-& and Visual .- all use t/e same integrated development environment
(01#)& 2/ic/ enables tool s/aring and eases t/e creation of mi3ed-language solutions. 0n
addition& t/ese languages use t/e functionality of t/e ."#$ 4rame2or*& 2/ic/ provides
access to *ey tec/nologies t/at simplify t/e development of S! %eb applications and
'() %eb Services.
T!pe of Application Architectures
pplications are developed to support organi5ations in t/eir business operations.
pplications accept input data& process t/e data based on business rules& and provide data
as output. $/e functions performed by as application can be divided into t/ree categories6
+ser Services
)usiness Services
Data Services
#ac/ category is implemented as a layer in an application.
+ser Services4 $/e user services layer constitute t/e front end of a solution. 0t is also
called a presentation layer because it provides an interactive user interface.
)usiness Services4 $/e business services layer controls t/e enforcement of business
rules on t/e data of an organi5ation. +usiness rules encompass t/ose practices and
activities t/at define t/e be/avior of an organi5ation. 4or e3ample& a ban* may /ave
decided t/at t/e credit limit of clients cannot e3ceed 7s.188888. $/e business services
layer performs validations pertaining to business rules. 0t ensures t/at t/e bac*-end does
not receive incorrect data.
Data Services4 $/e data service layer comprises t/e data and t/e functions for
manipulating t/is data.
$/ese t/ree layers form t/e base of t/e models or arc/itectures used into application
development.
Different type of architectures
$/ere are 4 types of pplication arc/itectures available6 t/ey are
4
5- Single/tier Architecture
0n Single-tier arc/itecture& a single e3ecutable file /andles all functions relating to t/e
user& business& and data service layers. $/is type of application is called monolit/ic
pplication. Single tier arc/itecture as given belo2
Single/tier Architecture
6- T&o/tier Architecture
$/e t2o-tier arc/itecture divides as application into t/e follo2ing t2o components
1. ,lient 6 0mplements t/e user 0nterface
2. Server 6 Stores 1ata
0n t/is arc/itecture& t/e user and data services are located separately& eit/er on t/e same
mac/ine or on separate mac/ines. 4or e3ample& V+ application provides t/e user
0nterface and (S S9)-Server manages t/e data.
$2o-$ier rc/itectures as given belo2
T&o/Tier Architecture
0n t/e t2o :tier arc/itecture& t/e business services layer may be implemented in one of
t/e follo2ing 2ays6
5
)! using fact client
)! using fat server
)! dividing the business services bet&een the user services and the data
services-
at Client4 0n fat ,lients& t/e business services layer is combined 2it/ t/e user
services layer. ,lients e3ecute t/e presentation logic and enforce business rules.
$/e server stores data and processes transactions. $/e fat client model is used
2/en t/e server is overloaded 2it/ transactions processing activities and is not
e;uipped to process business logic.
at Server4 %it/ a 4at server& t/e business service layer is combined 2it/ t/e
data services layer. s business services are stored on t/e server& most of t/e
processing ta*es place on t/e server.
)! dividing the business services bet&een the user services and the data
services4 <ou can also implement a t2o-tier model in 2/ic/ t/e business services
are distributed bet2een t/e user and data services. 0n t/e case& t/e processing of
t/e business logic is distributed bet2een t/e user and data services
7- Three/tier Architecture
0n t/e t/ree-tier arc/itecture& all t/e t/ree layers reside separately& eit/er on t/e same
mac/ine or on different mac/ines. $/e user interface interacts 2it/ t/e business logic.
$/e business logic validates t/e data sent by t/e interfaces and for2ards it to t/e database
if it conforms to t/e re;uirements. $/e front-end only interacts 2it/ business logic&
2/ic/& in turn& interacts 2it/ t/e database.
$/ree-tier rc/itecture as given belo2
Three/tier Architecture
8- n/tier Architecture
n n-tier application uses business ob=ects for /andling business rules and data access. 0t
/as multiple servers /andling business services. $/is application arc/itecture provides
various advantages over ot/er types of application arc/itectures. Some of t/e advantages
>
include e3tensibility& resilience to c/ange& maintainability& and scalability of t/e
application. (ost modern enterprise applications are based on t/e n-tier application
arc/itecture.
The .!"T Initiati#e
(icrosoft /as introduced t/e ."#$ initiative 2it/ t/e intention of bridging t/e gap in
interoperability bet2een applications. 0t aims at integrating various programming
languages and services. 0t is designed to ma*e significant improvements in code reuse&
code speciali5ation& resource management& multi-language development& security&
development and administration.
The .!"T %ra&e'or(
$/e ."et infrastructure consists of all t/e tec/nologies t/at /elp in creating and running
robust& scalable& and distributed applications. $/e core of t/e ."#$ infrastructure is
t/e ."#$ 4rame2or*& 2/ic/ is a collection of services and classes. 0t e3ists as a layer
bet2een ."#$ applications and t/e underlying operating system.
$/e ."#$ 4rame2or* provides t/e base for all development using VS 288?. 0t provides
base classes& available to all VS 288? languages for suc/ functions as accessing
databases& parsing '()& displaying and processing %indo2s and %eb forms& and
providing security for your applications. ll languages in Visual Studio 288? s/are and
use t/e same base classes& ma*ing your c/oice of a programming language in VS 288? a
matter of personal preference and synta3 style.
@
The .!"T %ra&e'or( *ase Classes or The .!"T class %ra&e'or(
$/e ."#$ class 4rame2or* consists of a class library t/at 2or*s 2it/ any ."#$
language& suc/ as Visual +asic. "#$& ,-& .- and Visual ,AA. $/is class library is built
on t/e ob=ect-oriented nature of t/e runtime. 0t provides classes t/at can be used in t/e
code to accomplis/ a range of common programming tas*s& suc/ as string management&
data collection& database connectivity& and file access. Bne of t/e most important features
of t/e ."#$ 4rame2or* class library is t/at it can be used in a consistent manner across
multiple languages. $/is means t/at you can use t/e same set of classes for performing a
specific tas* in V+ as 2ell as in VcAA.
!a&espace
"amespace /elp you to create logical groups of related classes and interfaces t/at can be
used by any language targeting t/e ."#$ 4rame2or*. "amespace allo2 you to organi5e
your classes so t/at t/ey can be easily accessed in ot/er applications. "amespaces can
also be used to avoid any naming conflicts bet2een classes t/at /ave t/e same names.
Asse&-lies
n assembly is a single deployable unit t/at contains all t/e information about t/e
implementation of classes& structures& and interfaces. n assembly stores all t/e
information about itself. $/is information is called metadata and includes t/e name and
version number of t/e assembly& security information& information about t/e
dependencies& and a list of t/e files t/at constitute t/e assembly. ll t/e applications
developed using t/e ."#$ 4rame2or* is also made up of assemblies. ssemblies and t/e
metadata provide t/e ,)7 2it/ t/e information re;uired for e3ecuting an application.

The Co&&on .anguage /unti&e
$/e common language 7untime is one of t/e most essential of t/e ."#$ 4rame2or*. $/e
,)7 or t/e runtime provides functionality suc/ as e3ception /andling& security&
debugging& and versioning support to any language t/at targets it. $/is means t/at t/e
runtime can /ost a variety of languages and offer a common set of tools across t/ese
languages& ensuring interoperability bet2een t/e codes.
5anaged Code e9ecution ,rocess
$/e process of compiling and e3ecuting managed code is given belo26
%/en you compile a program developed in a language t/at targets t/e ,)7&
instead of compiling t/e source code into mac/ine-level code& t/e compiler
translates it into (icrosoft 0ntermediate )anguage ((S0)) or 0ntermediate
?
language(0)). "o matter 2/ic/ language /as been used to develop t/e application&
it al2ays gets translated into 0).
0n addition to translating t/e code into 0)& t/e compiler also produces metadata
about t/e program during t/e process of compilation. (etadata contains t/e
description of t/e program& suc/ as t/e classes and interfaces& t/e dependencies&
and t/e versions of t/e components used in t/e program.
$/e 0) and t/e metadata are lin*ed in an assembly. $/e compiler creates t/e
-.9. or -DLL files.
%/en you e3ecute t/e -.9. or -DLL files& t/e code (converted into 0)) and all t/e
ot/er relevant information from t/e base class library is sent to t/e class loader.
$/e class loader loads t/e code in t/e memory.
+efore t/e code can be e3ecuted& t/e ."#$ 4rame2or* needs to convert t/e 0)
into native or ,!C-specific code. $/e .ust-0n-$ime (.0$) compiler translates t/e
code from 0) into managed native code. $/e ,)7 supplies a .0$ compiler for eac/
supported ,!C arc/itecture. 1uring t/e process of compilation& t/e .0$ compiler
compiles only t/e code t/at is re;uired during e3ecution instead of compiling t/e
complete 0) code.
1uring t/e .0$ compilation& t/e code is also c/ec*ed for type safety. $ype safety
ensures t/at ob=ects are al2ays accessed in a compatible 2ay. $/erefore& if you try
to pass ?-byte value to a met/od t/at accept 4-byte values its parameter& t/e ,)7
2ill detect and trap suc/ an attempt. $ype safety also ensures t/at ob=ects are
safely isolated from eac/ ot/er and are t/erefore safe from any in advertent or
malicious corruption.
fter translating t/e 0) into native code& t/e converted code is sent to t/e ."et
runtime manager.
$/e ."#$ runtime manager e3ecutes t/e code. %/ile e3ecuting t/e code& a
security c/ec* is performed to ensure t/at t/e code /as t/e appropriate permissions
for accessing t/e available resources.
D
The Diagram of Compilation and execution of a -N.T application as given belo&
,ompilation and #3ecution of a -N.T pplication
eatures Provided b! the CLR
Automatic Memory Management: $/e ,)7 provides t/e garbage collection
feature for managing t/e lifetime of an ob=ect. $/is process relieves a programmer
of t/e tas* of manual memory management by deallocating t/e bloc*s of memory
associated 2it/ ob=ects t/at are no longer being used.
Standard type system: $/e ,)7 implements a formal specification called t/e
,ommon $ype System(,$S) $/e ,$S is an important part of t/e support
provided by t/e ,)7 for cross-language integration because it provides a type
system t/at is common across all language.
Language interoperability: 0t is t/e ability of an application to interact 2it/
anot/er application 2ritten in a different programming language.
18
Platform independence: $/is feature provide your programs run on any mac/ine
(any platform) all ."#$ programs are ,!C-independent. $/is means t/at t/e code
can be e3ecuted from any platform t/at supports t/e -"#$ ,)7.
Security Management: The ."#$ platform provide security& it is ac/ieved t/roug/
t/e ,ode ccess Security (,S) model. 0n t/is model& t/e ,)7 enforces
restrictions on managed code t/roug/ t/e use of ob=ects called EpermissionsF.
Type Safety : $/e feature ensures t/at ob=ects are al2ays accessed in compatible
2ays.
Advantages of the -N.T rame&or:
Consistent programming model : all languages are ob=ect oriented model
Multi-platform applications 6 #3ecute program on '?> ,!C and >4 bit BS
Multi-language integration : 0t is an interoperability of multiple languages
Automatic resource management : 0t manages resources suc/ as files& memory&
"et2or* connections and database resources.
#ase of deployment 6 ."#$ application can be deployed simply by copying
files to t/e target computer.
Visual Studio 2008 ID"
$/e 2or*ing environment in Visual +asic is often referred to as t/e 0ntegrated
1evelopment #nvironment (01#)& because it integrates many different functions suc/ as
design& editing& compiling and debugging 2it/ in a common environment. Visual studio
01# /elps you to ma*e GC0 for t/e application program.

11
The "D. elements as given belo&
Toolbox6 $/e toolbo3 contains reusable controls and components t/at can be added to
your application. $/ese range from buttons to data connectors to customi5ed controls
t/at you /ave eit/er purc/ased or developed.
orms Designer *indo&4 $/e design 2indo2 is 2/ere a lot of t/e action ta*es
place. $/is is 2/ere you 2ill dra2 your user interface on your forms. form is t/e
basic unit in any 2indo2s-based application and is used to accept user input and
perform some action based on t/e input. 0t allo2 as you to add controls to a form&
arrange t/em as per your re;uirements& and add code to perform some actions. $/is
2indo2 is sometimes referred to as t/e 1esigner.
Solution .xplorer4 $/e Solution #3plorer 2indo2 contains a /ierarc/ical vie2 of
your solution. solution can contain many pro=ects& 2/ereas a pro=ect contains forms&
classes& modules& and components t/at solve particular problem.
Data Sources4 $/e 1ata sources 2indo2 allo2s you to connect to a database and
c/oose t/e database ob=ects for your application.
Properties4 $/e properties 2indo2 s/o2s 2/at properties t/e selected ob=ect ma*e
available. lt/oug/ you can set t/ese properties in your code& sometimes it is muc/
easier to set t/em 2/ile you are designing your application. property is a
c/aracteristic of an ob=ect& suc/ as si5e& te3t or color.
12
The output *indo&6 $/e output 2indo2 displays message for t/e status of various
features provided in t/e VS."#$ 01# 4or e3ample & 2/en you compile as application&
t/is 2indo2 displays t/e current status and after t/e compilation process is complete& it
specifies t/e number of errors t/at occurred during compilation
The Tas: List *indo&4 $/e tas* )ist 2indo2 displays a list of errors along 2it/ t/e
source of t/e error. 0t /elps you identify and locate problems t/at are detected
automatically as you edit or compile code. <ou can locate t/e source of a particular
error by simply double-clic*ing t/e error in t/e $as* )ist 2indo2.
Server .xplorer *indo& 4 $/e server e3plorer 2indo2 is a /andy tool for various
administrative tas*s suc/ as monitoring t/e performance of ot/er mac/ines on a
net2or*& and locating and connecting to t/e various servers on t/e net2or*. <ou can
also vie2 t/e different type of database connection details (S;l server& 1B."et&
B1+, ..etc). 0t also displays various ob=ects& suc/ as table& vie2s& and procedures t/at
can be accessed by using t/e data connection and resources of t/e services& suc/ as
services& processes& and t/e event log.
The D!namic ;elp *indo& 4 0t s provides you 2it/ conte3t-sensitive /elp. $/is
2indo2 is constantly updated to display t/e lin*s to t/e /elp topics on t/e current control&
component& or *ey2ord.
The Class <ie& *indo&4 $/e class Vie2 %indo2 displays t/e classes& met/ods& and
properties associated 2it/ a particular file.
The Code And Text .ditor *indo& 6 0t is allo2s you to enter and edit code and te3t.
$/is 2indo2 is called $/e code editor %indo2. <ou may use t/is 2indo2 to add code
for your form.
Navigational features 6 $/e VS."#$ 01# also provides t/ree navigational features.
1. 1oc*ing
2. $abbed "avigation
3. uto Hide
C4.!"T 2008 =C Sharp>
,-."#$ is a modern& ob=ect oriented language t/at enables programmers to ;uic*ly build
a 2ide range of applications for t/e ne2 (icrosoft."#$ platform& 2/ic/ provides tools
and services t/at fully e3ploit bot/ computing and communications.
,-."#$ is a great c/oice for arc/itecting a 2ide range of components-from /ig/-level
business ob=ects to system-level applications. Csing simple ,- language constructs& t/ese
13
components can be converted into '() %eb services& allo2ing t/em to be invo*ed
across t/e internet& from any language running on any operating system.
,-."#$ is a po2erful ob=ect-oriented language t/at provides features suc/ as abstraction&
encapsulation& in/eritance& and polymorp/ism. 0n addition& it provides many ot/er
features suc/ as multit/reading& structured e3ception /andlingIetc. ,- /elps you to
create solutions t/at run on t/e (icrosoft 2indo2s operating system& suc/ as %indo2s
Vista& %indo2s Server 288? and %indo2s (obile >.8. V+ 288? can also be used to
create 2eb applications and 2eb services as 2ell as mobile application t/at can run on
!oc*et !,s or Smart !/ones.
Introduction To Varia-les1 Constants
And Data Types.
,-."#$ li*e most programming languages uses variables for storing values. Variables
/ave a name and data type (2/ic/ determines t/e *ind of data t/e variables can store).
Constants also store values but as t/e name implies& t/ose values remain constant
t/roug/out t/e e3ecution of an application.
Declaring <ariables4 0n ,-."#$& you use variables to temporarily store values during
t/e e3ecution of an application. <ou declare a variable use follo2ing form& Statement
supplying a name for t/e variable& and also used public and private statement.
S!ntax 4 2Data t!pe3 2variable3=
$o declare General Variables& use !ublic Jey 2ord as t/e follo2ing form
S!ntax 4 public 2Data t!pe3 2variable3 =
$o declare private Variables& use !rivate *ey 2ord as t/e follo2ing form
S!ntax 4 private 2Data t!pe3 2variable3=
0n addition& t/e value of a variable in a met/od is local to t/at met/od- t/at is & you canFt
access a variable in one met/od from anot/er met/od. $/ese c/aracteristics allo2 you to
use t/e same variable names in different met/ods 2it/out 2orrying about conflicts or
accidental c/anges.
1eclaring a variable in t/e declarations section of a form& standard& or class
module& rat/er t/an 2it/ in a met/od& ma*es t/e variable available to all t/e
met/od in t/e module.
1eclaring a variable using t/e public *ey2ords ma*es it available t/roug/out
your application. $/ese type variables you can access outside t/e 2orld t/roug/
t/e ob=ect.
14
1eclaring a variable using t/e private *ey2ords ma*es it available t/roug/out
your application. +ut it is cannot access outside t/e 2orld.
1eclaring a local variable using static *ey2ord preserves its value even 2/en a
met/od ends.
.xample4
String name> housename =
int pin=
float price> 0uantit!=
Csing public Jey 2ord
public int number> age=
public string name=
Csing private Jey 2ord
private string name > house?name
private int number > reg?no=
*asic Data Types In C4.!"T
DATA T$P.S
$/e data type of variable determines /o2 t/e bits representing t/ose values are stored in
t/e computerFs memory. %/en you declare a variable& you can also supply a data type.
$/e Variant data type is li*e a c/ameleon : it can represent many different data types in
different situations.
The )asic Data T!pes as given belo&
T!pe Si#e @in bitsA Range
sbyte ? -12? to 12@
byte ? 8 to 255
s/ort 1> -32@>? to 32@>@
us/ort 1> 8 to >5535
int 32 -214@4?3>4? to 214@4?3>4@
uint 32 8 to 42D4D>@2D5
long >4 -D2233@283>?54@@5?8? to D2233@283>?54@@5?8@
ulong >4 8 to 1?44>@448@3@8D551>15
15
c/ar 1> 8 to >5535
string ,an contain 8 to 2billion Cnicode c/aracters
1ate$ime 0t is a class in t/e System namespace to /andle date time data
+oolean $o store true or false values only
loating Point and Decimal T!pes
,- floating point type is eit/er a float or double. $/ey are used any time you need to
represent a real number& as defined by 0### @54.
The Floating Point and Decimal Types with Size, precision, and Range
T!pe Si#e @in bitsA precision Range
float 32 @ digits 1.5 3 18
-45
to 3.4 3 18
3?

double >4 15-1> digits 5.8 3 18
-324
to 1.@ 3 18
38?

decimal 12? 2?-2D decimal places 1.8 3 18
-2?
to @.D 3 18
2?

C, -N.T Character .scape Se0uences
,- /as a special synta3 2/ere c/aracters can be escaped to represent non-printable
c/aracters. 4or e3ample& it is common to use ne2lines in te3t& 2/ic/ is represented by t/e
KLnK c/ar. $/e bac*slas/& KLK& represents t/e escape. %/en preceded by t/e escape c/aracter&
t/e KnK is no longer interpreted as an alp/abetical c/aracter& but no2 represents a ne2line.
<ou may be no2 2ondering /o2 you could represent a bac*slas/ c/aracter in your code.
%e /ave to escape t/at too by typing t2o bac*slas/es& as in KLLK. table 2-3 s/o2s a list of
common escape se;uences.
C# Character Escape Sequences
.scape
Se0uence
Meaning
LK Single 9uote
LM 1ouble 9uote
LL +ac*slas/
L8 "ull& not t/e same as t/e ,- null value
La +ell
Lb +ac*space
Lf form 4eed
Ln "e2line
1>
Lr ,arriage 7eturn
Lt Hori5ontal $ab
Lv Vertical $ab
Comments4 @BB or BCD-CBA
,omments are parts of a program t/at are ignored by t/e ,-."#$ 288? compiler& 2/ic/
means you can 2rite 2/atever you li*e in t/em. $o define comments in ,-."#$ use
double slas/ sign (NN) at t/e beginning of t/e line. $o ma*e multiline comments use
NOI.ON
#g6 BBdefine a variable for "umber
int "umber P
NO t/is is t/e coments
0t is an inter values
,annot store string values ON
2perators 3sed In C4.!"T
0n ,-."#$ use 4 type of operators. $/ey are6
5- Arithmetic %perators 4 0ts are Symbols t/at are used to perform arit/metic
operations on variables. ,ommonly used operators are given belo26
E
Csed to add t2o numbers
/
Csed to subtract t2o numbers
C
(ultiply t2o numbers
F
Csed to raise a number to t/e po2er of
anot/er number& called e3ponent
B
Csed to divide t2o numbers and return
floating number
G
Csed to divide t2o numbers and return
integer number
H
Csed to divide t2o numbers and return
t/e reminder
6- Assignment %perator
Q ssign value to t/e variable
Short hand Assignment %perator
AQ
QA1 AEI5
1@
/I
Q-1 A/I5
CI
QO1 ACI5
HI
QR1 AHI5
BI
QN1 ABI5
7- Comparison %perators 4 $/ese operators are used to compare t2o values and
perform and action based on t/e result of t/e comparison. Bperators are6
2 e3pr1 S e3pr2
Csed to c/ec* 2/et/er e3pr1 is lest/an e3pr2.
3 e3pr1 T e3pr2
Csed to c/ec* 2/et/er e3pr1 is grater e3pr2
2I e3pr1SQ e3pr2
Csed to c/ec* 2/et/er e3pr1 is lest/an or e;ual to
e3pr2
3I e3pr1 TQ e3pr2
Csed to c/ec* 2/et/er e3pr1 is grater or e;ual to
e3pr2
II e3pr1 QQe3pr2
Csed to c/ec* 2/et/er e3pr1 is e;ual to e3pr2
UI e3pr1UQ e3pr2
Csed to c/ec* 2/et/er e3pr1 is not e;ual to e3pr2
8- Logical %perators 6 0t is used to evaluate e3pressions and return a +oolean value.
VV ("1) e3pr1 VV e3pr2
7eturn true if e3pr1and e3pr2 is true
WW (B7) e3pr1 WW e3pr2
7eturn true if e3pr1 and e3pr2 is true or
t/e e3pr1 or e3pr2 is true
U ("B$) U e3pr
7eturn true if e3pr is false
J- "ncrement and Decrement %perator
AA (increase value 1) -- (decrease value 1)
K- Conditional %perator
X (true #3pression) 4 (false e3pression)
S!ntax 4 @conditionA L true e3pression 4 false e3pressionP
M- Concatenation %perators 4 ,oncatenation operators are used to =oin t2o
e3pressions.
E
Csed to concatenate t2o strings e3pression
N- Special %perators
si#eof@A $o find t/e lengt/ of ob=ectNvariable
chec:ed $o find t/e c/ec* state of t/e controls
unchec:ed $o find t/e unc/ec*ed state of t/e controls
t!peof $o c/ec* t/e controls is specified type
1?
Code 5odules In C4.!"T
,ode in ,-."#$ is stored in modules. $/ere are t/ree *inds of modules& 4B7(& and
,)SS. Simple applications can consist of =ust a single form and all of t/e code in t/e
application forms. <ou 2ant to e3ecute common code in several forms& for donFt 2ant to
duplicate t/e code in ot/er forms. So you create separate module containing a procedure
t/at implements t/e common code. $/is separate module s/ould be a standard module.
.ach Standard> class> and orm module can contain
Declarations- <ou can place constant& type& variable and 1ynamic :)in*
)ibrary(1))) met/od declarations at t/e form or class modules.
Method4 4unction& or !roperty met/ods contains pieces of code t/at can be
e3ecute as a unit.
1. orm Modules 4 4orm (odules (-CS file name e3tension and save t/e 1esigner
form-Designer-CS) are t/e foundation of most ,-."#$ applications. $/ey can
contain procedures t/at /andle events& general procedures& and form-level
declarations of variables& constants& types and e3ternal procedures.
2. Class Modules 4 ,lass (odules (Class-cs file name e3tension) are t/e foundation
of t/e ob=ect-oriented programming in ,-."#$. <ou can %rite code in class
modules to create ne2 ob=ects. $/ese ne2 ob=ects can include your o2n
customi5ed properties and met/ods. ctually forms are =ust class modules t/at can
/ave controls places on t/em and can display form 2indo2s.
To i&port li-raries
$o import e3ternal libraries into t/e program& to use t/e using statements as t/e follo2ing
form
using 2namespace3-O2sub namespace3P-Class
.g4 using S!stem-Convert=
using S!stem-*indo&s-orms-orm=
Console Applications
pro=ect for creating a command-line application (."#$ 4rame2or* 3.5). $o ma*e a
c/aracter user interface applications& you can use console application . 0ts e3ecute t/e ms-
dos operating system interface.
1D
#3ample of ,onsole application as given belo2
1. $o Bpen a "e& pro'ect (4ile-T"e2-T!ro=ect). $/en select )anguage (,-) and
c/oose option *indo&s under t/e specified language. nd Select Console
Appliaction icon from t/e rig/t pane of t/e dialog bo3.
2. $ype your pro=ect Name and Location (<ou 2ant to store your pro=ect into t/e
dis*)& clic* %:
("o2 open a console application and pro=ect S*elton as given belo2)
using Syste&A NNimporting class of libraries
NNYmore libraries are importedZ
na&espace csharpB1
C
class ,rogra&
C
static #oid 5ain=stringDE args>
C
Dprogra& state&entsE
F
D3ser Defined %unctionsE
F
Dclass declarationsE
F
Y$/en 2rite your code in side t/e module bloc*Z
.xample4 "nput 6 numbers and find the largest value
using SystemP
namespace cs/arp[1
\
class !rogram
\
static void (ain(stringYZ args)
\
int a&b& sP
,onsole.%rite)ine(M#nter t2o numbersM)P
a Q 0nt32.!arse(,onsole.7ead)ine())P
b Q 0nt32.!arse(,onsole.7ead)ine())P
s Q a A bP
,onsole.%rite)ine(MSumQ\8]M& s)P
,onsole.7eadJey()P
]
]
28
]
"mportant points
(ain() $/e met/od name (ain& is reserved for t/e starting point of a
program.
static $/e static modifier e3plains t/at t/is met/od 2or*s in t/is specific
class only& rat/er t/an instance of t/e class.
void 0s used to set t/e function does not return a value.
,onsole.%rite)ine() ^,onsole_ is a class in t/e System namespace. %rite)ine() is a
met/od in t/e ^,onsole_ class. $/is met/od is used to print t/e
specified data to t/e output.
QBBR $/ese are single line comments& meaning t/at t/ey are valid until t/e
end-of-line.
^BC_ and _CB_ $o specify everyt/ing in bet2een is part of comments.
=(semicolon)
0n c- all statements end 2it/ a semicolon.
S and T ll statements 2it/in and including ^\^ and ^]_ define a bloc*.
\8] & 0t is t/e formatted string for identify t/e printed data. $/e first format
string number is 8& t/e second is 1 and so on.
string YZ args 0s t/e string type arguments. 0t is refers to t/e argument array. $/e first
element of array is 8 and second is 1 and so on.
"nt76-Parse@ A : 0t is t/e class library& for used to convert c/ar data to integer. $/e
!arse() function are used 2it/ t/e all numeric data type for e3ample.
float.Parse(string s) : to convert value to single
double.Parse(string s) : to convert value to Double
decimal.Parse(string s):to convert value to Decimal
byte.Parse(string s):to convert value to Byte
char.Parse(string s):to convert value to Byte
C2!V"/T class li-rary
$o convert any type of data to appopriate type use ,onvert class )ibrary in S!stem
namespace

#3ample of some convert class members as given belo2
Convert.ToInt3(value) : data convert to integer
Convert.ToDouble(value) :data convert to Double ty!e
Convert.To"ingle(value) :data convert to "ingle ty!e
Convert.ToDecimal(value):data convert to Decimal
Convert.ToByte(value) :data convert to Byte ty!e
Convert.ToChar(value) :data convert to Char ty!e
21
Convert.To"tring(value) :data convert to "tring
Convert.ToBoolean(value):single digit data to beoolean ty!e
Convert.ToDateTime(value):data convert to date#time format
.g 6 4 /using Convert class member To"nt76@A U sum of t&o numbers
using SystemP
namespace cs/arp[1
\
class !rogram
\
static void (ain(stringYZ args)
\
int a&b& sP
,onsole.%rite)ine(M#nter t2o numbersM)P
a Q ,onvert.$B0nt32(,onsole.7ead)ine())P
b Q ,onvert.$o0nt32(,onsole.7ead)ine())P
s Q a A bP
,onsole.%rite)ine(MSum of \8] and \1]Q\2]M&a&b& s)P
,onsole.7eadJey()P
]
]
]
An Introduction to 5ethods
%/ile developing an application& you may need to use t/e same code in multiple parts of
t/e applications. 7epeating code often leads to problems in maintaining it. 4or e3ample&
if c/ange one part of t/e code& t/e c/ange needs to be replicated in every sections of t/e
application 2/ere t/e code is repeated. $o avoid suc/ situations& you can use (et/ods
(et/od is a set of one or more program statements t/at can be e3ecuted by referring to
t/e met/od name. (et/ods are t/e *ey to modular programming. %/en a comple3
application is divided into met/ods& t/e code is more fle3ible and easy to maintain and
debug.
$/ere are t2o type of met/ods in ,- ."#$ 6
Returnnon return type methods
Property methods
7eturn type met/ods are return a value into t/e calling from called function. 0tFs type is
type of return value& suc/ as int& float& c/ar& string etc.
22
$/e non return type functions are defined 2it/ void *ey 2ord. Void *ey2ord is used to
tell t/e compiler to t/is function is not returned a value.
Synta3 of met/ods
2Access Modifier3 2t!pe3 2method name3@ arguments listA
S
Statements=
T
Access Modifiers
public 0t is accessible from any2/ere 2it/in and outside of t/e application.
$/is is default access mode
protected 0t is accessible only from 2it/in its o2n class or from derived class
private 0t is accessible only from 2it/in its declaration conte3t& including
any nested met/ods
.xample 4 to add t2o numbers and display sum& (Bpen a ,onsole application and 2rite
t/e follo2ing code)
using SystemP
namespace cs/arp[1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram pr Q ne2 !rogram()P NNob=ect creation
pr.sum()P NNmet/od calling
,onsole.7eadJey()P
]
private void sum()
\
int a& b& sP
,onsole.%rite)ine(M#nter t2o numbersM)P
a Q 0nt32.!arse(,onsole.7ead)ine())P
b Q 0nt32.!arse(,onsole.7ead)ine())P
s Q a A bP
,onsole.%rite)ine(MSum of \8] and \1]Q\2]M&a&b& s)P
]
]
]
23
Propert! methods
property met/od is a set of code statements t/at are used to assign or retrieve t/e
values of t/e properties declared 2it/in a class or a structure. !roperties are type of
variables t/at store t/e values for an ob=ect of a class or a structure.
$/ere are t2o type of property procedure in ,-."#$
get : met/od are used to retrieve t/e value from a property
set : met/od are used to assign values to a property to set value& use value statement
S!ntax6
public 2t!pe3 2propert! name3
S
getS return 2value3T
set S variableIvalue= T
T
.xample6 $o print t/e sum of t2o numbers& using property met/ods
using SystemP
namespace cs/arp[1
\
class !rogram
\
private int a& b& sP
static void (ain(stringYZ args)
\
!rogram pr Q ne2 !rogram()P NNob=ect creation
pr.no1 Q 188P NNproperty calling
pr.no2 Q 288P
,onsole.%rite)ine(M"o 1Q\8]M&pr.no1)
,onsole.%rite)ine(M"o 2Q\8]M&pr.no2)
pr.sum()P NNmet/od calling
,onsole.7eadJey()P
]
public int no1 NNdefine property
\
get \return aP ]
set\ a Q valueP ]
]
public int no2 NNdefine property
\
get \return bP ]
set \ b Q valueP ]
24
]

public void sum()
\
s Q a A bP
,onsole.%rite)ine(MSum Q\8]Ms)P
]
]
]
Arguments @ParametersA
$/e argument list is used to send values bet2een met/ods. $o specifies arguments into
t/e function& use follo2ing form
publicBprivate 2t!pe3 2methodname3@ 2t!pe3 var5> 2t!pe3 var6>D-A
S
)od! of the methods=
T
.xample4 4ind product of t2o numbers
using SystemP
namespace cs/arp[1
\
class !rogram
\
static void (ain(stringYZ args)
\
int a& bP
,onsole.%rite)ine(M#nter 2 numbersM)P
a Q ,onvert.$o0nt32(,onsole.7ead)ine())P
b Q ,onvert.$o0nt32(,onsole.7ead)ine())P
!rogram pr Q ne2 !rogram()P NNob=ect creation
pr.sum(a&b)P NNcalling met/od 2it/ parameters
,onsole.7eadJey()P
]

public void sum(int 3& int y) NNdefine met/od 2it/
parameters
\ int sP
s Q 3 A yP
,onsole.%rite)ine(MSum of \8] and \1]Q\2]M&3&y& s)P
]

]
25
]
Method return a <alue
met/od is a bloc* of statements. $/e return type met/ods return a value to t/e calling
met/od from t/e called met/od. $o return a value from t/e met/od& use return *ey2ord
and not use void *ey2ord as t/e met/od type.
S!ntax4
2Access Modifier3 2t!pe3 2method name3@ arguments listA
statements
return 2value3
.nd sub
.xample4 $o calculate average of t2o numbers
using SystemP
namespace cs/arp[1
\
class !rogram
\

static void (ain(stringYZ args)
\
float avP
!rogram pr Q ne2 !rogram()PNNob=ect creation
avQpr.verage()P
,onsole.%rite)ine(MverageQ\8]M& av)P
,onsole.7eadJey()P
]
public float verage()
\
float a& b&sP
,onsole.%rite)ine(M#nter 2 numbersM)P
a Q float.!arse(,onsole.7ead)ine())P
b Q float.!arse (,onsole.7ead)ine())P
s Q (aAb)N2P
return sP
]

]
]
2>
Control Structures
,ontrol structure is t2o categories. $/ey are 1#,0S0B" ma*ing and )BB!0"G
statements. $/e control statements are used to control t/e e3ecution flo2 of t/e statement
based on t/e specified conditions in t/e program.
D.C"S"%N MAV"NW STAT.M.NTS
$/e decision ma*ing statements are used into t/e program to control t/e flo2 of t/e
program e3ecution. <ou can apply your o2n conditions to t/e programP t/is is done by
using decision statements. $/ey are
1. if statement
2. s&itch statement
if Statement. 0t is po2er full decision ma*ing statement in ,-. Cse an if statement
to e3ecute one or more statements conditionally.
Syntax :
if (condition
!
true statements"
#
$lse
!
false Statements"
#
.g4 "nput 7 numbers and find the larget number
using SystemP
namespace cs/arp[1
\
class !rogram
\

static void (ain(stringYZ args)
\
!rogram pr Q ne2 !rogram()P
pr.largest()P
,onsole.7eadJey()P
]
public void largest()
\
2@
int a& b&cP
,onsole.%rite)ine(M#nter 3 numbersM)P
a Q 0nt32.!arse(,onsole.7ead)ine())P
b Q 0nt32.!arse (,onsole.7ead)ine())P
,onsole.%rite(M)argestQM& a)P
if (a T b)
,onsole.%rite)ine(M\8]M& a)P
else
,onsole.%rite)ine(M\8]M& b)P
]

]
]
ifDelse if ladder statement
0t is a multi decision ma*ing format. See t/e follo2ing e3ample
if (condition %
!
Statements %"
#
else if(condition &
!
Statements &"
#
'''''''''''(
''''''''''
else if(condition n
!
Statements n"
#
else
!
false Statements"
#
.xample 4 $o input a number t/at is represents t/e day of t/e 2ee*. $/en display t/e
corresponding day.
using SystemP
namespace cs/arp[1
\
class !rogram
\
2?
static void (ain(stringYZ args)
\
!rogram pr Q ne2 !rogram()P
pr.1ay[Bf[%ee*()P
,onsole.7eadJey()P
]

public void 1ay[Bf[%ee*()
\
int dayP
,onsole.%rite)ine(M#nter a number(1-@)6M)P
day Q 0nt32.!arse(,onsole.7ead)ine())P
,onsole.%rite(M$/e day is M)P
if (dayQQ1)
,onsole.%rite)ine(MSC"1<M)P
else if (dayQQ2)
,onsole.%rite)ine(M(B"1<M)P
else if (dayQQ3)
,onsole.%rite)ine(M$C#S1<M)P
else if (dayQQ4)
,onsole.%rite)ine(M%#1"#S1<M)P
else if (dayQQ5)
,onsole.%rite)ine(M$HC7S1<M)P
else if (dayQQ>)
,onsole.%rite)ine(M4701<M)P
else if (dayQQ@)
,onsole.%rite)ine(MS$C71<M)P
else
,onsole.%rite)ine(M(invalid day number you enterd)M)P

]
]
]
s&itch statement-
,- provides t/e s2itc/ as an alternative to if else for selectively e3ecuting one bloc* of
statements from among multiple bloc*s of statements. s2itc/ 2or*s 2it/ a single test
e3pression t/at is evaluated once& at t/e top to bottom cases& 0f t/ere is a matc/ case
found t/en e3ecute t/e t/at case associated statements and control =ump to t/e out of t/e
s2itc/ statement
The general form of s&itch
s&itch @ test exper-A
S
2D
case 2exper 534
S
statements 5=
brea:=
T
case 2exper 634
S
statements 6=
brea:=
T
DDDDDDD--
DDDDDD
case 2exper n34
S
statements n=
brea:=
T
default 4
S
Statements=
brea:=
T
T
Example: modify above program to use switch
using SystemP
namespace cs/arp[1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram pr Q ne2 !rogram()P
pr.1ay[Bf[%ee*()P
,onsole.7eadJey()P
]
public void 1ay[Bf[%ee*()
\
int dayP
,onsole.%rite)ine(M#nter a number(1-@)6M)P
day Q 0nt32.!arse(,onsole.7ead)ine())P
,onsole.%rite(M$/e day is M)P
s2itc/ (day)
38
\
case 16
\
,onsole.%rite)ine(MSC"1<M)P
brea*P
]
case 26
\
,onsole.%rite)ine(M(B"1<M)P
brea*P
]
case 36
\
,onsole.%rite)ine(M$C#S1<M)P
brea*P
]
case 46
\
,onsole.%rite)ine(M%#1"#S1<M)P
brea*P
]
case 56
\
,onsole.%rite)ine(M$HC7S1<M)P
brea*P
]
case >6
\
,onsole.%rite)ine(M4701<M)P
brea*P
]
case @6
\
,onsole.%rite)ine(MS$C71<M)P
brea*P
]
default6
\
,onsole.%rite)ine(M(invalid day number
you enterd)M)P
brea*P
]
]
]]]
31
.22,I!< STAT"5"!TS
,- provides t/ree types of looping statements. $/ese are used to repetitive e3ecution of
t/e specified bloc* of statements no of times for meet t/e specified condition is true. $/e
available looping statements are
5- &hile loop statement
6- do --&hile loop statement
7- for loop statement
*hile loop statement6
$/is is an anot/er entry controlled loop . $/e general form as given belo2
S!ntax4 2/ile ( )condition*
\
''''''''(
Statements
''''''''(
#
.g4 $o print t/e odd numbers bet2een 1 to 25 and t/eir sum
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\ int 3Q1&s Q 8P
,onsole.%rite)ine(Mdisplay valuesM)P
2/ile(3SQ15)
\
,onsole.%rite)ine(M\8]M&3)P
s Q s A 3P
3 Q 3 A 2P
]
32
,onsole.%rite)ine(MSum of odd numbersQ\8]M& s)P
,onsole.7eadJey()P
]
]
]
doD-&hile statement
0t is treated as entry controlled and #3it controlled loop met/od. 0t is used to repeats a
bloc* of statements 2/ile a condition is true or until a condition becomes true.
S!ntax 4 .xit Controlled loop
do
!
'''''''
Statements bloc+"
'''''''
#,hile ( )condition*"
*;"L. Clause 4 $/is clause is used to c/ec* t/e condition is true t/e e3ecute t/e
statements& %/en t/e condition becomes false t/e loop e3ecution 2ill terminate.
.xample4$o print first 18 integers and t/eir sum
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\ int 3Q1&s Q 8P
,onsole.%rite)ine(Mdisplay valuesM)P
do
\
,onsole.%rite)ine(M\8]M&3)P
s Q s A 3P
3AAP
]
2/ile(3SQ18)P
,onsole.%rite)ine(MsumQ\8]M & s)P
,onsole.7eadJey()P
33
]
]
]
%R loop statements
0t is an entry controlled loop& t/at is used to repeats a group of statement specified no of
times. $/e general form as given belo2
S!ntax 4
for(initiali-ation"condition"increment.decrement
!
'''''''((
Statement bloc+
'''''
#
.xample6 To Print even numbers bet&een 5 to 6X
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\ int 3Q1&s Q 8P
,onsole.%rite)ine(Mdisplay valuesM)P
for(3Q1P3SQ28P3AA)
\
if(3R2QQ8)
,onsole.%rite)ine(M\8]M&3)P
]
,onsole.7eadJey()P
]
]
]
.xample6 To Print values 5X to 5 @bac:&ard readingA
34
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\ int 3Q1&s Q 8P
,onsole.%rite)ine(M1isplay valuesM)P
for(3Q18P3TQ1P3--)
,onsole.%rite)ine(M\8]M&3)P
,onsole.7eadJey()P
]
]
]
foreach loop statement@0t is an anot/er type of for loopA
$/is loop is used to read values from t/e collection suc/ as array. $/e general form as
given belo2
Synta36
foreach @StypeT SveriableT in collection[array)
S
IIIIIII
StatementsP
IIIIIIII.
T
( #3ample of foreach loop provided in array section)
The A//A7S
$/e array facility is used to create an array variable and to store large amount of valuesNor
ot/er data to specified type as single name. $2o types of arrays are available in visual
basic
1. %ne dimensional array
2. T&o dimensional array
35
3. Multi dimensional array
%ne dimensional arra! 4 list of data can be stored to t/e specified variable and its
used only one subscript& t/ese variables also called one dimensional array. $o declare
one dimentional array& use t/e follo2ing form.
2t!pe3O P variableI ne& t!peOsi#eP=

.g4 intO P numbersIne& intO5XP=
$o store ten different numbers to t/e variable ^numbers_& of t/e type int.
.g4 $o store ten numbers into t/e array and find t/eir sum
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\
intYZ 3Q ne2 intY18ZP NNarray declaration
int yP
,onsole.%rite)ine(M#nter 18 valuesM)P
for(yQ8PyS18PyAA)
3YyZ Q int.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(Mdisplay array valuesM)P
for(yQ8PyS18PyAA)
,onsole.%rite)ine(M\8]M&3YyZ)P
,onsole.7eadJey()P
]
]
T
T*% dimensional arra! 4 list of data can be stored to t/e specified variable as t/e
form of matri3& and its used t2o subscript(ro2 and column)& t/ese variables also called
t2o dimensional array. $o declare t2o dimensional array& use t/e follo2ing form.
2t!pe3O > P I ne& t!peOsi#e> si#eP=
.g4 intY & Z matQne2 intY3& 3ZP
3>
0n t/is variable contains 3 ro2s and 3 columns. $otal D elements are found in t/is
arrays
Multi dimensional Arra! Declaration
2t!pe3O > > P I ne& t!peOsi#e> si#e> si#eP=
.g4 intY & & Z matQne2 intY3& 2&3ZP
.xample4 $o store values in 3 3 3 array and print it in t/e form of matri3
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(string YZ args)
\
int 3&yP
intY&Z no Q ne2 intY3& 3ZP
,onsole.%rite)ine(Menter numbersM)P
for (3 Q 8P 3 S 3P 3AA)
for (y Q 8P y S 3P yAA)
noY3& yZ Q int.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(Mdisplay arry valuesM)P

for (3 Q 8P 3 S 3P 3AA)
\
for (y Q 8P y S 3P yAA)
,onsole.%rite(M\8] M& noY3& yZ)P
,onsole.%rite(MLnM)P
]
,onsole.7eadJey()P
]
]
]
Arra! "nitiali#ation
0nitiali5ation is give value to t/e array variable at t/e declaration time. $o initiali5e
values into t/e array& you can use t/e follo2ing form
Synta3 of one dimentional array
3@
2t!pe3O P variableISvaluesT=
.g4
int YZ numberQ\1&2&3&4&5]
stringY Z nameQ\^nu_&_run_&_noop_&_7eena_]
S!ntax of T&o dimentional arra!
2t!pe3O > P IS SvaluesT>SvaluesT>D-T
.g4
intY & Z numberQ\\1&2&3]&\4&5&>]]
StringY & Z nameQ\\^nu_&_23_]& \_run_&_15_]&
\_noop_&_1>_]&\_7eena_&_1>_]]
.xample4 $o store 18 number and print it
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\
intYZ no Q \ 1& 2& 3& 4& 5& >& @& ?& D& 18 ]P
int 3P
,onsole.%rite)ine(M1isplay valuesM)P
for (3 Q 8P 3 S no.)engt/ P 3AA)
,onsole.%rite)ine(M\8] M& noY3Z)P
,onsole.7eadJey()P

]
]
]
+sing foreach Loop
3?
.xample 5. $o store 18 number and print it
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\
stringYZ name Q \ ManuM& MarunM& MreenaM& M=o/nM ]P
,onsole.%rite)ine(M1isplay namesM)P
foreac/ (string na in name)
\
,onsole.%rite)ine(M\8]M& na)P
]
,onsole.7eadJey()P

]
]
]
.xample4 T&o dimensional arra! initiali#ation
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(string YZ args)
\
int 3&yP
intY & Z no Q \ \1&5&>]& \1&2&3]& \3&4&5] ]P
,onsole.%rite)ine(Menter numbersM)P

for (3 Q 8P 3 S 3P 3AA)
\
for (y Q 8P y S 3P yAA)
,onsole.%rite(M\8] M& noY3& yZ)P
,onsole.%rite(MLnM)P
3D
]
,onsole.7eadJey()P
]
]
]
Passing Arra!s as Parameters
0tFs #3tremely useful to be able to pass an array( 2/ic/ could be a list of values) to a
function as a parameter.
.xample4
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
stringYZ name Q \ ManuM& MarunM& MreenaM& M=o/nM ]P
!rogram p Q ne2 !rogram( )P
p.1isplay[Values(name)P NNpassing arguments
]
public void 1isplay[Values(stringYZ nam)
\

,onsole.%rite)ine(M1isplay namesM)P
foreac/ (string na in nam)
\
,onsole.%rite)ine(M\8]M& na)P
]
,onsole.7eadJey()P

]
]
]
Arra! class
0t is sometime useful to be able to sort& 7everse & 7esi5e and find )engt/ of an array.&
t/is is done by using rray class 2it/ met/ods of Sort& 7everse& )engt/..etc.
$o use Sort met/od as given belo2
Synta36 Arra!-Sort@arra! variableA
48
To ind arra! length
$o find t/e array lengt/& use lengt/ met/od. $/e useage as given belo2
Synta36
2arra! variable3-length
.xample4 to store 18 numbers in an array and display sorted values
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
stringYZ name Q \ M`eenaM& MarunM& MreenaM& M+iniM&M=o/nM]P
!rogram p Q ne2 !rogram()P
p.1isplay[Values(name)P
]
public void 1isplay[Values(stringYZ nam)
\

,onsole.%rite)ine(M1isplay sorted namesM)P
rray.Sort(nam)P
foreac/ (string na in nam)
\
,onsole.%rite)ine(M\8]M& na)P
]
,onsole.7eadJey()P

]
]
]
Reversing an arra!
$o reverse t/e array value& you can use t/e Reverse met/od of t/e rray class.

Synta36 Arra!-Reverse@2arrra! variable3A
using SystemP
namespace ,onsolepplication1
\
41
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\
intYZ no Q \ 1& 2& 3& 4& 5& >& @& ?& D& 18 ]P
,onsole.%rite)ine(M1isplay reversed valuesM)P
rray.7everse(no)P
foreac/ (int n in no)
\
,onsole.%rite)ine(M\8]M& n)P
]
,onsole.7eadJey()P

]
]
]
D!namic Arra!s
%/en using an array& if you 2ant to c/ange its si5e in order to add items& or clean up
space 2/en you remove items& you need to use t/e 7esi5e() met/od of t/e array class to
ma*e dynamic array.
Synta36
Arra!-Resi#e@ref 2arra! variable3>2 ne& si#e3A
.g4
intYZ noQne2 intY5ZP
rray.7esi5e(re! no&18)P
$o resi5e t/e specified array& in t/e 7esi5e met/od& t/e first argument is t/e array nameP
you must specify ref *ey2ord before t/e array name and set t/e ne2 si5e as second
argument.
.xample4 $o store 18 numbers first and 7esi5e t/e array of 5 and add ne2 five numbers
t/en print it
using SystemP
namespace ,onsolepplication1
42
\
class !rogram
\
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
]
public void 1isplay[Values()
\
intYZ no Q \ 1& 2& 3& 4& 5& >& @& ?& D& 18 ]P
,onsole.%rite)ine(M1isplay reversed valuesM)P
rray.7esi5e(ref no& 15)P NNc/ange t/e array si5e
noY18Z Q 28P NNadding ne2 value into t/e array
noY11Z Q 38P
noY12Z Q 48P
noY13Z Q 58P
noY14Z Q >8P
foreac/ (int n in no)
\
,onsole.%rite)ine(M\8]M& n)P
]
,onsole.7eadJey()P

]
]
]
"nu&eration Type
$/e enum *ey2ord is used to declare an enumeration& a distinct t!pe t/at consists of a
set of named constants called t/e enumerator list. #very enumeration t!pe /as an
underlying t!pe& 2/ic/ can be any integral t!pe e3cept char. $/e default underlying type
of t/e enumeration elements is int. +y default& t/e first enumerator /as t/e value 8& and
t/e value of eac/ successive enumerator is increased by 1. 4or e3ample6
enum 1ays \Sat& Sun& (on& $ue& %ed& $/u& 4ri]P
$o create enumeration datatype use follo2ing form
Synta36
enum 2variable3O4 2t!pe3PSvaluesT=
.g4 enum values SoneI5>t&o>three>four>fiveT=
enum values 4 int SoneI5>t&o>three>four>fiveT=
43
.xample
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
enum 7ange 6 long \ (a3 Q 214@4?3>4?)& (in Q 255) ]P
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
,onsole.7eadJey()P
]
public void 1isplay[Values()
\
long 3 Q (long)7ange.(a3P
long y Q (long)7ange.(inP
,onsole.%rite)ine(M(a3 Q \8]M& 3)P
,onsole.%rite)ine(M(in Q \8]M& y)P
]
]
]
.xample 64
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
enum 1ays \SatQ1& Sun& (on& $ue& %ed& $/u& 4ri]P
static void (ain(stringYZ args)
\
!rogram p Q ne2 !rogram()P
p.1isplay[Values()P
,onsole.7eadJey()P
]
public void 1isplay[Values()
\
int 3 Q (int)1ays.SunPint y Q (int)1ays.4riP
,onsole.%rite)ine(MSun Q \8]M& 3)P
,onsole.%rite)ine(M4ri Q \8]M& y)P
]
]
44
]
S!stem-lagsAttribute type
$/e follo2ing code e3ample illustrates t/e use and effect of t/e S!stem-lagsAttribute
attribute on an enum declaration.
using SystemP
namespace ,onsolepplication1
\
Y4lagsZpublic enum ,arBptions
\
Sun7oof Q1&
Spoiler Q 2&
4og)ig/ts Q 4&
$inted%indo2s Q?&
]
class !rogram
\
static void (ain(string YZ args)
\
,arBptions options Q ,arBptions.Sun7oof W ,arBptions.4og)ig/tsP
,onsole.%rite)ine(options)P
,onsole.%rite)ine(^$otal of optionsQ_&(int)options)P
,onsole.7eadJey()P
]
]
]
ST3/CT3/" in C4.!"T
,-."#$ supports a constructed data type *no2n as Structure& 2/ic/ is a met/od for
pac*ing data of different types. structure is a convenient tool for /andling a group of
logically related data items. <ou can also declare properties and events as structure
members. $o define a structure use& struct *ey2ord as t/e follo2ing form.
struct 2 structure name3
\
S access modifier T StypeT variable P
S access modifier T StypeT variableP
IIIIIIIIIIIIIIIII
IIIIIIIIIIIIIIIII.
property 1efinition
45
]
Access modifiers 4 <ou can specify t/e access scope of a structure using access
modifiers. ccess modifiers for t/e structure are listed in t/e folo2ing table.
public public members accesible from any 2/ere 2it/in or outside
t/e application. $/is is default access mode
protected protected members accessible only from 2t/in its o2n class
or from a derived class
friend friend members is accessible from 2it/in t/e program t/at
contain its declaration and from any 2/ere else in t/e
same program
protected
friend
protected riend members accessible from 2it/in t/e same
assembly and in t/e derived class.
.g4 struct product
S
public int itemnoP
!ublic string itemnameP
!ublic float itemprice P
public float item9tyP
T
$o access structure members& you create an ob=ect of structure and use ob=ect 2it/ dot
operator as t/e follo2ing form
.g4
product pro= BB in this method> does not access propert!
or
product proIne& product@ A=
1eclares EproF as t/e ob=ect of type struct product.
ccess members 6 use 1B$ operator 2it/ t/e ob=ect
pro-itemno
pro-itemnamne

.xample 4 input a student details and print it
using SystemP
namespace ,onsolepplication1
\
struct student
4>
\
public int no& ageP
public string name& se3P
]
class !rogram
\
static void (ain(string YZ args)
\
student sP NNob=ect of structure
s.no Q188P
s.nameQM.o/nMP
s.se3 QM(aleMP
s.ageQ28P
,onsole.%rite)ine(M"umberQ\8]M&s.no)P
,onsole.%rite)ine(M"ame Q\8]M&s.name)P
,onsole.%rite)ine(Mge Q\8]M&s.age)P
,onsole.%rite)ine(MSe3 Q\8]M&s.se3)P
,onsole.7eadJey()P
]
]
]
Adding propert! to structure
.xample 6 $o 2rite and display student name and age using properties
using SystemP
namespace ,onsolepplication1
\
struct student
\
private int noP
private string nameP
public int getnumber NNproperty 1
\
get \ return noP ]
]
public int setnumber NNproperty 2
\
set \ noQvalueP ]
]
public string getname NNproperty 3
\
4@
get \ return nameP ]
]
public string setname NNproperty 4
\
set \ name Q valueP ]
]

]
class !rogram
\


static void (ain(string YZ args)
\
student s Q ne2 student()P P NNob=ect of structure
s.setnumber Q188P NNproperty calling
s.setname Q M1ennyMP
,onsole.%rite)ine(M"umberQ\8]M&s.getnumber)P
,onsole.%rite)ine(M"ame Q\8]M&s.getname)P
,onsole.7eadJey()P
]
]
]
ARRA$ %f Structure
%e use structures to describe t/e format of anumber of related variables. 4or e3ample& to
store t/e student details of class& 2e may use a template to describe student details in a
class& you 2ant to store all student details int t/e structure&to declare an array of structure&
eac/ element of t/e array representing a structure variable. 0t is t/e convenient 2ay to
/old any details as table format for future manipulation of t/e data.
$o declare array of structure as given belo26
S!ntax4 2structure t!pe3O P 2variable3I ne& 2structure t!pe3Osi#eP=
.g4 product OP proIne& productOJP=

1eclare proOJP as t/e variable array of t/e type struct product. $o /old 5 product
details into t/e struct pro array.
.xample4 $o input 5 product details and print eac/ of t/em-
using SystemP
namespace ,onsolepplication1
4?
\
struct product
\
public int inoP
public string inameP
public float ipriceP
public float i;tyP
]
class !rogram
\


static void (ain( stringYZ args)
\
productYZ pr Q ne2 productY5ZP NNstructure array ob=ect
int 3P
for (3 Q 8P 3 S 5P 3AA)
\
,onsole.%rite)ine(Menter "umberM)P
prY3Z.ino Q int.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(Menter item nameM)P
prY3Z.iname Q ,onsole.7ead)ine()P
,onsole.%rite)ine(Menter item priceM)P
prY3Z.iprice Q float.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(Menter item ;uantityM)P
prY3Z.i;ty Q float.!arse(,onsole.7ead)ine())P
]
,onsole.,lear()P
,onsole.%rite)ine(Mdisplay item detailsM)P
for (3 Q 8P 3 S 5P 3AA)
\
,onsole.%rite)ine(M0tem "umber Q\8]M&prY3Z.ino )P
,onsole.%rite)ine(M0tem name Q\8]M&prY3Z.iname )P
,onsole.%rite)ine(M0tem price Q\8]M&prY3Z.iprice )P
,onsole.%rite)ine(M0tem ;uantityQ\8]M& prY3Z.i;ty)P
,onsole.%rite)ine(M-----------------------------M)P
]
,onsole.7eadJey()P
]
]
]
Structure as Method arguments
namespace ,onsolepplication1
\
struct product
4D
\
public int inoP
public string inameP
public float ipriceP
public float i;tyP
]
class !rogram
\
static void (ain(String YZ arg)
\
!rogram pg Q ne2 !rogram()P
product pr Q ne2 product()P NNstructure ob=ect
,onsole.%rite)ine(Menter "umberM)P
pr.ino Q int.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(Menter item nameM)P
pr.iname Q ,onsole.7ead)ine()P
,onsole.%rite)ine(Menter item priceM)P
pr.iprice Q float.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(Menter item ;uantityM)P
pr.i;ty Q float.!arse(,onsole.7ead)ine())P

pg.getdata(pr)P

,onsole.7eadJey()P
]

public void getdata(product p)
\
,onsole.,lear()P
,onsole.%rite)ine(Mdisplay item detailsM)P

,onsole.%rite)ine(M0tem "umber Q\8]M& p.ino)P
,onsole.%rite)ine(M0tem name Q\8]M& p.iname)P
,onsole.%rite)ine(M0tem price Q\8]M& p.iprice)P
,onsole.%rite)ine(M0tem ;uantityQ\8]M& p.i;ty)P
,onsole.%rite)ine(M-----------------------------M)P
]
]
]
2-8ect 2riented ,rogra&&ing in C4.!"T
,- ."et is an ob=ect oriented programming language& and it supports all t/e four pillars of
ob=ect oriented programming& 2/ic/ are encapsulation> abstraction> inheritance> and
pol!morphism-
58
$/e ."#$ frame2or* provides some predefined classes& 2/ic/ you can use in ,-."#$
applications. 4or e3ample if you create a 2indo2s application& t/e form added to t/e
application in/erits eit/er from t/e System.%indo2s.4orms.4orm base class or from
anot/er e3isting form. $o /andle e3ceptions in a ,-."#$ application& you use t/e System
namespace. 0n addition& you can create your o2n classes to use t/em in ,-."#$
application.
Class
class is a conceptual representation of all t/e entities t/at s/are common attributes and
be/aviors. 0t defines t/e attributes and be/aviors t/at are used by all t/e instance of t/at
class. 4or e3ample& you can create a class called Person t/at defines t/e common
attributes& suc/ as color and height> and common be/aviors& suc/ as tal: and &al:> for
all t/e instances of t/e class.
%b'ect
n ob=ect is an instance of a class. ll t/e ob=ects of a class /ave individual copies of t/e
attributes and s/are a common set of be/aviors. 4or e3ample6 1evid and 1ery are
ob=ects of t/e !erson class. +ot/ t/ese ob=ects can /ave individual copies of color and
height attributes and tal: and &al: be/aviors.
Advantages of +sing Classes and %b'ects
1. (aintenance of code by introducing modularity
2. #ncapsulation of internal comple3ities in code from end-users
3. 7euse of code across applications
4. support for a single interface to implement multiple met/ods.
eatures of C,-N.T
Some of t/e BB!s *ey 4eatures of ,-."#$ as given belo2
"nheritance
Constructors and destructors
%verloading
%verriding
Structured exception handling
Multithreading
Defining a Class
$o define a class& use class *ey2ord as t/e follo2ing form.
51
S!ntax4
2access modifier3 class 2Class name3
S
(ember variable declaration
YpublicNprivate (et/od 1efinitionsZ
YpublicNprivate !roperty 1efinitionsZ
]
"ote 6 ccess modifiers are publicBprivate- $/e default access modifier is private-
Creating %b'ects 4
$o create an ob=ect of t/e class& use ne& operator as t/e follo2ing form
Synta36 classname 2ob'ect3 I ne& classname@A=
.xample4 to input an employee details and print it
using SystemP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
employee em Q ne2 employee()P NNcreate ob=ect of class employee
em.emp[details()P NNcalling met/od
]
]
NNne2ly created class
class employee
\
struct employ
\
public int enoP
public string nameP
public string designationP
public float salaryP
]
public void emp[details()
\
52
employ emp Q ne2 employ() P NNob=ect of structure

,onsole.%rite)ine(Menter "umberM)P
emp.eno Q int.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(Menter nameM)P
emp.name Q ,onsole.7ead)ine()P
,onsole.%rite)ine(Menter designationM)P
emp.designation Q ,onsole.7ead)ine()P
,onsole.%rite)ine(Menter salaryM)P
emp.salary Q float.!arse(,onsole.7ead)ine())P
,onsole.,lear()P
,onsole.%rite)ine(Mdisplay item detailsM)P
,onsole.%rite)ine(M"umber Q\8]M& emp.eno)P
,onsole.%rite)ine(Mname Q\8]M& emp.name)P
,onsole.%rite)ine(M1esignationQ\8]M& emp.designation)P
,onsole.%rite)ine(Msalary Q\8]M& emp.salary)P
,onsole.7eadJey()P
]
]
]
Constructors and Destructors
+sing Constructors
0t is an automatically e3ecutable met/od at t/e time of ob=ects creation. ,onstructors are
special met/ods t/at allo2 control over t/e initiali5ation of ob=ects. ,onstructors /ave t/e
same name as t/e class itself. Secondly& t/ey do not specify a return type& not even void&
and you must specify t/e type modifier as public or private only.
#3ample6
class Test
S
public Test@A NN constructor definition 0tFs name& same as class name
S
OStatements=P
T
Oclass methods definitionsP=
T
.xample of using constructors
using SystemP
53
namespace $est,onstructor
\
class !rogram
\
static void (ain(stringYZ args)
\
sample sa Q ne2 sample()P
sa.sum()P
,onsole.7eadJey()P
]
]
class sample
\
int a& bP
public sample() NNconstructor met/od
\
,onsole.%rite)ine(M#nter 2 numbers6M)P
a Q 0nt32.!arse(,onsole.7ead)ine())P
b Q 0nt32.!arse(,onsole.7ead)ine())P
]
public void sum()
\
int s Q a A bP
,onsole.%rite)ine(MSumQ\8]M& s)P
]
]
]
+sing Destructors
1estructors are special met/ods t/at are used to release t/e instance of a class from
memory. $o e3ecute t/e destructor automatically& it is does not calling manually.
Remar:s
1estructors cannot be defined in structs. $/ey are only used 2it/ classes.
class can only /ave one destructor.
1estructors cannot be in/erited or overloaded.
1estructors cannot be called. $/ey are invo*ed automatically.
destructor does not ta*e modifiers or /ave parameters.
$o define destructor use tiled (Y) sign beginning of t/e constructor. 4or e3ample
54
class Test
S
public Test@A NN constructor definition 0tFs name& same as class name
S
OStatements=P
T
public YTest@A NN destructor definition
S
OStatements=P
T
Oclass methods definitionsP=
T
.xample4 using 4inali5e( ) and 1ispose ( ) met/ods
using SystemP
namespace $est1estructor
\
class !rogram
\
static void (ain(stringYZ args)
\
sample saQ ne2 sample()P
sa.product()P
,onsole.7eadJey()P
]
]

class sample
\
int a& bP
public sample() NNconstructor met/od
\
,onsole.%rite)ine(M#nter 2 numbers6M)P
a Q 0nt32.!arse(,onsole.7ead)ine())P
b Q 0nt32.!arse(,onsole.7ead)ine())P
]
public void product()
\
int s Q a O bP
,onsole.%rite)ine(MproductQ\8]M& s)P
]
55
asample() NNdestructor met/od
\
,onsole.%rite)ine(M1estructor invo*ed and remove t/e
constructor from t/e memoryM)P
,onsole.7eadJey()P
]
]
]
unction %verloading4
Bverloading enables met/ods to be defined 2it/ t/e same name but different parameters.
0n ot/er 2ord& it allo2s you to /ave multiple implementations of a met/od. 0n ,-."#$ &
you can create multiple met/ods 2it/ t/e same name in a class provided t/eir parameters
list is different.
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
b Q ne2 ()P
b.display(18)P
b.display(18&28)P
b.display(5&>&3)P
,onsole.7eadJey()P
]
]
class
\
public void 7esult(int 3)
\
,onsole.%rite)ine(MS;uare of \8]Q\1]M&3&3O3)P
]
public void 7esult(int 3& int y)
5>
\
,onsole.%rite)ine(MSum of \8]&\1]Q\2]M&3&y&3Ay)P
]
public void 7esult(int 3& int y& int 5)
\
,onsole.%rite)ine(M!roduct of \8]&\1]&\2]Q\3]M&3&y&5&3OyO5)P
]
]
!a&espaces
0t is mainly used to create class library. $/e namespaces are naming sc/eme t/at /elps
you to organi5e t/e classes available in an application so t/at t/ey can be easily found.
"amespace enable you to avoid name collisions. "ame collisions occur 2/en multiple
classes 2it/ t/e same name perform different tas*s. $o calling function in t/e pro=ect
t/ere 2ill be a conflict in t/e name. to avoid suc/ situations& you can use namespaces in
,- ."#$ applications.
$o create name spaces use namespace statement as follo2ing form
S!ntax4
namespace SnameT
\
SmodifierT class SnameT
\
IIIIIII..
]

SmodifierT class SnameT
\
IIIIIIII
]
IIIIIIIII.
YSub namespace declartionZ
]
.xample 4 using namespaces
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
using NStest-subtest= NN namespace importing
5@
using NStest=
namespace $est"ameSpace
\
class !rogram
\
static void (ain(stringYZ args)
\
sum s Q ne2 sum()P
s.getsum()P
product p Q ne2 product()P NN sub name space class ob=ect
p.getproduct()P
,onsole.7eadJey()P
]
]
]
namespace "Stest NN ne2ly created namespace
\
class sum
\
int a&b&cP
public void getsum()
\
,onsole.%rite)ine(M#nter 2 numbersM)P
a Q ,onvert.$o0nt32(,onsole.7ead)ine())P
b Q ,onvert.$o0nt32(,onsole.7ead)ine())P
c Q a A bP
,onsole.%rite)ine(MSumQM A c)P
]
]
namespace subtest NNsub namespace of "Stest
\
class product
\
int 3& y& pP
public void getproduct()
\
,onsole.%rite)ine(M#nter 2 numbersM)P
3 Q ,onvert.$o0nt32(,onsole.7ead)ine())P
y Q ,onvert.$o0nt32(,onsole.7ead)ine())P
p Q 3 O yP
,onsole.%rite)ine(M!roductQM A p)P
]
]
]
5?
]
"b6 in t/e above e3ample& t/e TestNameSpace is t/e pro=ect name and NStest is
namespace and t/e Subtest is t/e sub namespace of "Stest
$o e3plicitly call any class from t/e namespace you must import your namespace at t/e
top of t/e pro=ect.& using using *ey2ord as t/e follo2ing form
.g4 using 2pro'ectname3-2namespace3-2classname3=
To define Class .i-rary
class library is a collection of classes t/at compile to a file6 a %indo2s 1ynamic )in*
)ibrary (1))& or -dll file). <ou cannot run a class library by itself& but you can use t/e
classes in it from your applications. <ou can use a class library 2it/out t/e source codeP
it does not need to be recompiled 2/en t/e application is compiled& and if t/e library
c/anges& t/e applications using it 2ill automatically get t/e advantage of t/e improved
code.
1. $o open a ,lass)ibrary module (4ile-Tne2-Tpro=ect-T ,lass)ibrary)
2. ,/ange t/e !ro=ect name as ^$est)ibrary_& t/en clic* BJ
3. "e2 open ,lass library pro=ect and activate a class & remeve t/at class module
and 2rite t/e follo2ing code
namespace "Stest
\
public class ,alc
\
public int sum(int 3&int y)
\
int s Q (3 A y)P
return sP
]

public int product(int 3&int y)
\
int p Q (3 A y)P
return pP
]
public float verage(int 3&int y)
\
float f Q ((float)(3 A y))N2P
return fP
5D
]
]

public class calcVolumes
\
public double ,irclerea(float 3)
\
double s Q (at/.!0 O 3 b 2P
return sP
]

public double Vol,ylinder(int 3&int y)
\
double p Q (at/.!0 O 3 b 2 O yP
return pP
]

public double VolSp/eare(int 3)
\
double vs Q 4 N 3 O (at/.!0 O 3 b 3P
return vsP
]
]
]
4. 4inally +uild t/e solutions and close t/e pro=ect
<ou can use previously created library into t/e application& <ou add t/e reference of t/e
library into t/e pro=ect and use using statement to import library.
1. $/en open a ne2 ^,onsole application_ pro=ect
2. Select pro=ect menu and c/oose t/e option ^dd 7eference_
3. 1ialog bo3 appears. Selct +ro2se $ab and c/oose your 1ebug directory from t/e
^$est)ibrary_ folder ($est)ibrary-T $est)ibrary -T+in-T1ebug)
4. ,lic* B*. "o2 add t/e library into t/e your pro=ect.
$/en %rite t/e follo2ing code into t/e pro=ect run it.
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
using TestLibrar!= NNimport e3ternal )ibrary
namespace ,onsolepplication2
\
>8
class !rogram
\
static void (ain(stringYZ args)
\
int aP
double vP
,alc ,Q ne2 ,alc()P
calcVolumes ,VQ ne2 calcVolumes()P
a Q ,.sum(18& 28)P
,onsole.%rite)ine(MSumQM A a)P
a Q ,.product(5& ?)P
,onsole.%rite)ine(M!roductQM A a)P
v Q ,.verage(5& ?)P
,onsole.%rite)ine(Mverge QM A v)P
v Q ,V.,irclerea(18)P
,onsole.%rite)ine(Mrea of circleQM A v)P
v Q ,V.Vol,ylinder(18& 28)P
,onsole.%rite)ine(MVolume of cylinderQM A v)P
v Q ,V.VolSp/eare(18)P
,onsole.%rite)ine(MVolume of sp/eareQM A v)P
,onsole.7eadJey()P
]
]
]
/ote: 0 This class Library methods are declare in static1 all methods directly called in
any method ( ,ith out ob2ect of class3
Inheritance
0n/eritance is t/e ability of a class to derive its c/aracteristics from an e3isting class.
Csing ,-."#$& you can create a class t/at provides basic functionality so t/at ot/er
classes can in/erit its members. $/e general form as given belo2.
S!ntax
class 2DerivedClass3 4 2)aseClass3
S
Member declarations=
MethodBpropert! definitions=
T
.xample of declaration4
class +ase,lass
\
(ember declarationsP
(et/od definitionsP
>1
]
class 1erived,lass 4 +ase,lass NNin/eritance declaration
\
(ember declarationsP
(et/od definitionsP
]
0n ,-."#$ provides 5 type of 0n/eritance. $/ey are
5- Single "nheritance
6- Multilevel "nheritance
7- ;ierarchical "nheritance
8- Multiple "nheritance
J- ;!brid "nheritance
5- Single "nheritance
>2
.xample 4
using SystemP
namespace Single0n/eritance
\
class !rogram
\
static void (ain(stringYZ args)
\
Single1erived S1 Q ne2 Single1erived()P
S1.display+ase()P
S1.display()P
,onsole.7eadJey()P
]
]
class Single+ase NN+ase class
\
public void display+ase()
\
,onsole.%rite)ine(M0 am in +ase classM)P
]
]
class Single1erived 6 Single+ase NN1erived ,lass
\
public void display()
\
,onsole.%rite)ine(M0 am in 1erived classM)P
]
]
]
6- Multilevel "nheritance
.xample4
using SystemP
namespace $est(ultilevel
\
class !rogram
\
static void (ain(stringYZ args)
\
1erived,lass 1, Q ne2 1erived,lass()P
1,.display+ase()P
>3
1,.disp0base()P
1,.disp1erived()P
,onsole.7eadJey()P
]
]
class +ase,lass NN+ase ,lass
\
public void display+ase()
\
,onsole.%rite)ine(M0 am in +ase classM)P
]
]
class 0nter+ase,lass6 +ase,lass NNintermediate +ase class
\
public void disp0base()
\
,onsole.%rite)ine(M0 am in inter. +ase classM)P
]
]
class 1erived,lass 6 0nter+ase,lass NN1erived class
\
public void disp1erived()
\
,onsole.%rite)ine(M0 am in 1erived classM)P
]
]
]
7- ;ierarchical inheritance
.xample4
using SystemP
namespace $estHierarc/ical
\
class !rogram
\
static void (ain(stringYZ args)
\
1erived,lass1 1,1 Q ne2 1erived,lass1()P
1erived,lass2 1,2 Q ne2 1erived,lass2()P
1,1.display+ase()P
1,1.disp1erived1()P
>4
1,2.display+ase()P
1,2.disp1erived2()P
,onsole.7eadJey()P
]
]
class +ase,lass NN+ase ,lass
\
public void display+ase()
\
,onsole.%rite)ine(M0 am in +ase classM)P
]
]
class 1erived,lass16 +ase,lass NN1erived class 1
\
public void disp1erived1()
\
,onsole.%rite)ine(M0 am in 1erived class 1M)P
]
]
class 1erived,lass2 6 +ase,lass NN1erived class 2
\
public void disp1erived2()
\
,onsole.%rite)ine(M0 am in 1erived class 2M)P
]
]
]
Yprovid e3ample of (ultipleNHybrid 0n/eritanceZ
Interfaces in C4.!"T
0n ,-."#$ /as full support for interfaces. n interface defines properties& met/ods. $/e
properties& met/ods are defined in t/e interface are *no2n as t/e members of t/e
interface. 0t is important to note t/at interfaces contain only t/e declaration of members.
,lasses and structures in/erit t/ese interfaces members.
$o define interface use interface *ey2ord as t/e follo2ing form.
S!ntax4
interface Sinterface nameT
\
(et/od declarationsP
>5
!roperty declarationsP
]
.xample4 0nput an 0tems name and to store a class 0tems and get t/e 0tem name
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace $est0nterface
\
interface product
\
void getdata()P
void display()P
]
class !rogram
\

static void (ain(string YZ arg)
\
product p Q ne2 0$#(S()P
p.getdata()P
p.display()P
p.gettotal()P NNcanKt access t/is met/od t/roug/ t/e interface
NNob=ect& because it is not a member of interface

0$#(S ( Q ne2 0$#(S()P
NN $o access classNinterface met/ods t/roug/ t/e class ob=ect&
(.getdata()P
(.display()P
(.gettotal()P

,onsole.7eadJey()P
]
]
class "T.MS 4 product (in/erits interface)
\
int no& price&;tyP
string nameP
public void getdata() NNinterface memeber
>>
\
,onsole.%rite)ine(M#nter item detailsM)P
,onsole.%rite)ine(M0tem "umberM)P
no Q 0nt32.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(M0tem "ameM)P
name Q ,onsole.7ead)ine()P
,onsole.%rite)ine(M0tem ;tyM)P
;ty Q 0nt32.!arse(,onsole.7ead)ine())P
,onsole.%rite)ine(M0tem priceM)P
price Q 0nt32.!arse(,onsole.7ead)ine())P
]
public void display() NNinterface memeber
\
,onsole.,lear()P
,onsole.%rite)ine(Mdisplay item detailsM)P

,onsole.%rite)ine(M0tem "umber Q\8]M& no)P
,onsole.%rite)ine(M0tem name Q\8]M& name)P
,onsole.%rite)ine(M0tem price Q\8]M& price)P
,onsole.%rite)ine(M0tem ;uantityQ\8]M& ;ty)P
,onsole.%rite)ine(M-----------------------------M)P

]
public void gettotal() NNclass member
\
int tot Q price O ;tyP
,onsole.%rite)ine(M$otal !riceQ\8]M& tot)P
]

]
]
"nterface "nheritance
<ou can in/erits t/e interfaces. $o in/erits interfaces& using same in/eritance met/od of
class. $/e general form as given belo2
S!ntax4
interface derived0nterface 4 +ase0nterface
S
IIIIII..
(embers of derived0nterface
IIIIIII..
T
>@
or example 6 0n/erits t2o interfaces and implements t/e derived interface into t/e class
$o display student details (no&name&sub=ect mar*&language mar* and total)
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication>
\
interface +ase0nterface
\
void get+ase()P
]
interface derived0nterface 4 +ase0nterface
\
void get1erived()P
]
class !rogram
\
static void (ain(stringYZ args)
\
,onsole.%rite)ine(MLn---------+ase interface Bb=ect---------LnM)P
+ase0nterface + Q ne2 0nterface0n/eritance()P
+.get+ase()P
,onsole.%rite)ine(MLn---------1erived interface Bb=ect---------LnM)P
derived0nterface 1 Q ne2 0nterface0n/eritance()P
1.get+ase()P
1.get1erived()P
,onsole.%rite)ine(MLn---------,lass Bb=ect---------LnM)P
0nterface0n/eritance , Q ne2 0nterface0n/eritance()P
,.get+ase()P
,.get1erived()P
,.get,lass()P
,onsole.7eadJey()P
]
]
>?
class 0nterface0n/eritance 6 derived0nterface
\
public void get+ase()
\
,onsole.%rite)ine(M0 am base 0nterface memberM)P
]
public void get1erived()
\
,onsole.%rite)ine(M0 am 1erived 0nterface memberM)P
]
public void get,lass()
\
,onsole.%rite)ine(M0 am derived class memberM)P
]
]
]
.xample of "nterface &ith Propert! methods
$o input your firm name and print itX
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication>
\
interface $est0nterface
\
void 1isplay()P
string get"ame NNread only property
\
getP
]

string set"ame NN%rite only property
\
setP
]
]
>D
class !rogram
\

static void (ain(stringYZ args)
\
!roperty$est ! Q ne2 !roperty$est()P
!.set"ame Q M(0,$MP
,onsole.%rite)ine(M"ameQM A !.get"ame)P NNprint name
!.1isplay()P NN print name
,onsole.7eadJey()P
]
]
class !roperty$est 6 $est0nterface
\
string nameP
public string get"ame
\
get
\
return nameP
]

]
public string set"ame
\
set
\
nameQvalueP
]

]
public void 1isplay()
\
,onsole.%rite)ine(M"ameQMAname)P
]
]
]
Multiple "nheritances
.xample4$o input student number and name t/e display it &using interface and class
@8
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication>
\
interface disp1ata
\
void 1isplay()P
]
class student"ame
\
protected string nameP
public void get"ame()
\
,onsole.%rite)ine(M#nter student "ameM)P
name Q ,onsole.7ead)ine()P
]
]
class (ar* 6 student"ame & disp1ata NNmultiple in/ertance
\
int m1& m2P
public void get(ar*()
\
,onsole.%rite)ine(M#nter 2 mar*sM)P
m1 Q 0nt32.!arse(,onsole.7ead)ine())P
m2 Q 0nt32.!arse(,onsole.7ead)ine())P
]
public void 1isplay()
\
,onsole.%rite)ine(M"ameQMAname)P
,onsole.%rite)ine(M(ar*1QMAm1)P
,onsole.%rite)ine(M(ar*2QM A m2)P
]
]
class !rogram
\

static void (ain(stringYZ args)
\
(ar* ( Q ne2 (ar*()P
@1
(.get"ame()P
(.get(ar*()P
(.1isplay()P

,onsole.7eadJey()P
]
]
]
"ND.9.R in C,-N.T
!rovide s/ort note-----------------------------------------------------------
#3ample of using 0nde3er in ,- program
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication1
\
class !rogram
\
static void (ain(stringYZ args)
\
$est0nde3er $ Q ne2 $est0nde3er(18)P

$Y5Z Q 188P
$Y@Z Q 288P
,onsole.%rite)ine(Mdisplay all valuesM)P
for (int = Q 8P = S 18P =AA)
,onsole.%rite)ine(MValuesQM A $Y=Z)P
,onsole.7eadJey()P

]
]
class $est0nde3er
\
private intYZ dataP

@2
public $est0nde3er(int si5e)
\
data Q ne2 intYsi5eZP
for (int i Q 8P i S si5eP iAA)
\
dataYiZ Q 8P
]
]
public int t/isYint posZ
\
get \ return dataYposZP ]
set \ dataYposZ Q valueP ]
]
]
]
Structured "9ception handling
#3ceptions are t/e errors t/at are generated at runtime as a result of an erroneous
statement or condition or because of some une3pected be/avior of t/e application.
,-."#$ supports structured e3ception /andling t/at consists of protected bloc*s of code
and filters for t/e possible e3ceptions t/at can be raised by t/e program to c/ec* t/e
#3ceptions using tr!Dcatch Dfinall! statements as t/e follo2ing form
S!ntax
tr!
\
IIIII.
Statements
IIIII
]
catch@ S#3ceptionT SBb=ectT)
S
Statements
]
Ofinall!P
S
Statement
]
.xample4 t/e follo2ing e3ample /andles t/e general e3ception
using SystemP
using System.,ollections.GenericP
using System.)in;P
@3
using System.$e3tP
namespace ,onsolepplication>
\
class !rogram
\
public void getdata()
\
int a& b& cP
try
\
,onsole.%rite)ine(M#nter number 1 6M)P
a Q ,onvert.$o0nt32(,onsole.7ead)ine())P
,onsole.%rite)ine(M#nter number 2 6M)P
b Q ,onvert.$o0nt32(,onsole.7ead)ine())P
c Q a A bP
,onsole.%rite)ine(MSumQM A c)P
]
catc/ (#3ception e3)
\
,onsole.%rite)ine(e3.(essage)P
]
]
static void (ain(stringYZ args)
\
!rogram ! Q ne2 !rogram()P
!.getdata()P

,onsole.7eadJey()P
]
]
]
In the above e$am!le% you in!ut a character data then dis!lay the follo&ing
error message
'In!ut string &as not in a correct format.(
$/is is an e3ample of general e3ception /andling.
Some exception are given belo&
%e can /andle t/e predefined e3ception. 0n ,-."#$ many predefined e3ception are
available& some are described as given belo2
.xception Description
@4
4ormat#3ception 0nput invalid format data
rit/metic#3ception $/e e3ception t/at is t/ro2n for errors in an
arit/metic& casting& and conversion operation
Bverflo2#3ception $o e3ceed t/e limit of variable (datatype)
"ull7eference#3ception $/e e3ception t/at is t/ro2n 2/en t/ere is an
attempt to dereference a null ob=ect reference
1uplicate"ame#3ception duplicate database name encountered during an
add operation of dataset related ob=ect
rgument#3ception $/e e3ception t/at is t/ro2n 2/en one of t/e
arguments provided to a met/od is not valid
0nvalid,ast#3ception $/e e3ception t/at is t/ro2n for invalid casting
or e3plicit conversion
0nsufficient(emory#3ception $/e e3ception t/at is t/ro2n 2/en a c/ec* for
sufficient available memory.
rray$ype(imatc/#3ception $/e e3ception t/at is t/ro2n 2/en an attempt is
made to store an element of t/e 2rong type
2it/in an array
0nde3ButBff7ange#3ception %/en an attempt is made to access an element of
an array 2it/ an inde3 out of bounds of t/e
array
"ote6 (any more e3ceptions are available in ,-."#$
.xample4 of numeric overflo2 error
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication>
\
class !rogram
\
public void getdata()
\
byte a&b&cP
try
\
,onsole.%rite)ine(M#nter number 1 6M)P
a Q +yte.!arse(,onsole.7ead)ine())P
NN range only 8 to 255& so generate e3ception
b Q +yte.!arse(,onsole.7ead)ine())P
c Q(byte)(a A b)P
,onsole.%rite)ine(MSumQM A c)P
]
catc/ (Bverflo2#3ception e3)
\
@5
,onsole.%rite)ine(e3.(essage)P
]
]
static void (ain(stringYZ args)
\
!rogram ! Q ne2 !rogram()P
!.getdata()P

,onsole.7eadJey()P
]
]
]
Y#3ecute t/e above e3mple and type value more t/an 255 t/en display t/e e3ception.Z
5ultiple e9ceptions
$o c/ec* t/e multiple e3ception at a time using try..catc/ statement as t/e follo2ing
form
S!ntax
tr!
\
IIIII.
Statements
IIIII
]
catch@ S#3ceptionT SBb=ectT)
S
Statements
]
catch@ S#3ceptionT SBb=ectT)
S
Statements
]
catch@ S#3ceptionT SBb=ectT)
S
Statements
]
IIIIII..
Ofinall!P
S
Statement
]
@>
Example: to !rovid an e$am!le
3ser defined "9ceptions
0n ,-."#$& you can create your o2n e3ception& and t/e e3ecution of used defined
e3ceptions& use thro& statement as t/e follo2ing form
S!ntax4
Thro& ne& 2user defined exception3@messageA
.xample4 See t/e follo2ing e3ample to create user defined e3ception
)odule )odule*
"ub )ain()
getdata()
Console.+ead,ey()
-nd "ub
Public "ub getdata()
Dim a .s Byte% b .s Integer% c .s Integer
Try
Console./rite0ine(1-nter number:1)
a 2 Convert.ToInt3(Console.+ead0ine())
b 2 Convert.ToInt3(Console.+ead0ine())
If b 2 3 Then
Thro& 4e& DivisionBy5ero-rror(1The second value
connot be 5ero1)
-nd If
c 2 a 6 b
Console./rite0ine(1"um21 7 c)
Catch e$ .s DivisionBy5ero-rror
Console./rite0ine(e$.)essage())
8inally
Console./rite0ine(1I am in main !rogram1)
-nd Try
-nd "ub
-nd )odule
Class DivisionBy5ero-rror
Inherits -$ce!tion
Public "ub 4e&() 9default constructor
-nd "ub
Public "ub 4e&(By:al mes .s "tring) 9overload constructor
)yBase.4e&(mes)
-nd "ub
@@
-nd Class
The Delegates
Delegates 4 $/e delegates feature are t/e pointer accessing met/ods in ,-."#$ . 0ts
similar to t/e cNcAA !ointers
1elegates are ob=ects you can use to call t/e met/ods of ot/er ob=ects. $/ey are
sometimes described as type-safe function pointers because t/ey are similar to function
pointers used in ot/er programming languages. +ut unli*e function pointers& Visual +asic
delegates are a reference type based on t/e class System.
$o point delegates to any function as given belo2. 4irst declare a delegate function at t/e
top of t/e program& use Delegate statement as t/e follo2ing form
Syntax:
Delegate void testdelegate@A=
nd assign t/e address of t/e specified function t/e delegates& to declare one delegate
ob=ect and e3ecute t/e delegate& use invo:e met/od .
S!ntax4
2delegate unction3 2ob'ect3 I ne& 2delegate function@methodBfunctionA=
.xample4 to calculate sum of t2o numbers
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication>
\
delegate void testdelegate()P

class !rogram
\
int a&b&cP

public void getnos()
\
,onsole.%rite)ine(M#nter t2o numbersM)P
a Q ,onvert.$o0nt32(,onsole.7ead)ine())P
@?
b Q ,onvert.$o0nt32(,onsole.7ead)ine())P
]

private void getsum()
\
c Q a A bP
,onsole.%rite)ine(MSumQM A c)P
]
static void (ain(stringYZ args)
\
!rogram ! Q ne2 !rogram()P
testdelegate 1Q ne2 testdelegate(!.getnos)P
1.0nvo*e()P
testdelegate 4Q ne2 testdelegate(!.getsum)P
4.0nvo*e()P
,onsole.7eadJey()P
]
]
]
Delegates &ith parameters
.xample 6 $o calculate product of t2o numbers
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication>
\ delegate void testdelegate1()P
delegate void testdelegate2(int 3&int y)P
class !rogram
\
static int a&b&cP

public void getnos()
\
,onsole.%rite)ine(M#nter t2o numbersM)P
a Q ,onvert.$o0nt32(,onsole.7ead)ine())P
b Q ,onvert.$o0nt32(,onsole.7ead)ine())P
]
private void getsum(int 3& int y)
\
c Q 3AyP
,onsole.%rite)ine(MSumQM A c)P
@D
]
static void (ain(stringYZ args)
\
!rogram ! Q ne2 !rogram()P
testdelegate1 1Q ne2 testdelegate1(!.getnos)P
1.0nvo*e()P
testdelegate2 4Q ne2 testdelegate2(!.getsum)P
4.0nvo*e(a&b)P
,onsole.7eadJey()P
]
]
]
Class delegates
$/e follo2ing e3ample describe t/e calling class met/ods t/roug/ class delegates and
(odule level delegates.
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
namespace ,onsolepplication>
\ delegate void testdelegate1(int 3)P
delegate void testdelegate2(int 3&int y)P
class !rogram
\

static void (ain(stringYZ args)
\
,alc , Q ne2 ,alc()P
testdelegate1 1Q ne2 testdelegate1(,.getS;uare)P
1.0nvo*e(5)P
testdelegate2 4Q ne2 testdelegate2(,.get!roduct)P
4.0nvo*e(18&28)P
,onsole.7eadJey()P
]
]
]
dd a class (!ro=ects-Tdd ,lass ) and 2rite t/e follo2ing code
public class ,alc
\
?8
int a& b& cP
public void getS;uare(int 3)
\
c Q 3 O 3P
,onsole.%rite)ine(MS;uare QM A c)P
]
public void get!roduct(int 3& int y)
\
c Q 3 O yP
,onsole.%rite)ine(M!roductQM A c)P
]
]
I:2 %ile 5anage&ent
0n as application variables and arrays used to store data. Ho2ever& t/e storage of data in
variables and arrays is temporary. $o store data permanently& you need to use file-
file is a collection of bytes t/at /as a persistent storage. $/e data in a file is stored as
data streams and 2/en you need from or 2rite to a file& you read and 2rite data as data
streams.
data stream is se;uence of bytes t/an can be 2ritten to or read from a bac*up devices&
suc/ as a /ard dis*. $o save and retrieve data& you need to perform file inputNoutput
operations. $/e file iNo operations involve reading from and 2riting to files.
,-."#$ allo2s you to perform file iNo operations in t2o different 2ays6
1. using t/e ."#$ system 0NB model
2. Csing t/e ,-."#$ runtime functions.
3sing Syste&.I2 &odel
0n ,-."#$ & you can use t/e System.0B model for t/e file /andling. $/e System.0B
model specifies a set of classes t/at are available to all t/e ."#$ languages. $/ese classes
are used for creating& copying& moving& and deleting files. $/e most fre;uently used
classes in t/e System.0B namespace are ileStream> )inar!Reader> )inar!*riter>
StreamReader> Stream*riter and Director! <ou can use t/ese classes to rerad from
or 2rite to files.
The ileStream Class 4
?1
$/is class provides access to files and file-related information. $/e 4ileStream class is
used 2it/ t/e 4ile class& 2/ic/ is also contained in t/e System.0B namespace& to create&
copy delete& move and open files.
$/e 4ileStream class opens a file eit/er in sync/ronous or async/ronous mode. 0n
sync/ronous made& $/e entire file is first read and t/en displayed to t/e user. 0n
async/ronous mode a visual basic application starts reading and displaying a file in parts&
2it/out 2aiting for t/e entire file to be read first and t/en displayed.
$/e met/ods used to open a file in sync/ronous mode are Read@A and *rite@A and t/e
met/ods used to open a file in async/ronous mode are )eginRead() and )egin*rite@A-
+y default& 4ilestream opens files in Sync/ronous mode.
$/e constructors of t/e 4ileStream class use enumerations& suc/ as 4ile(ode& 4ile
ccess& and 4ileS/are& to specify /o2 a file is created and s/ared.
ileMode .numerations
ppend 0t is used to add data to t/e end of t/e e3isting file& or
create a ne2 file. ppend can only be used 2it/
4ileccess.%rite
,reate $o create a ne2 file& if file is already e3ists it 2ill be
over2ritten.
,reate"e2 $o create a ne2 file& if file is already e3ists it 2ill be
t/ro2 an e3ception.
Bpen $o open an e3isting file.
BpenBr,reate $o Bpen an e3isting file or ,reate ne2 file
$runcate $o open an e3isting file and clear all contents.
ileAccess Mode
7ead 0t is used to specify 7ead access to a file so t/at data can be
read from t/e file
7ead%rite $o read and %rite access to a file so t/at data can be 2ritten to
and read from t/e file
%rite $o %rite access to a file so t/at data can be 2ritten to t/e file.
The ileShare Mode
7ead 0t is used to decline s/aring of t/e current file.specify 7ead
access to a file so t/at data can be read from t/e file
7ead%rite $o read and %rite access to a file so t/at data can be 2ritten to
and read from t/e file
?2
%rite $o %rite access to a file so t/at data can be 2ritten to t/e file.
.xample of ile Creation
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
using S!stem-"%= NNimport class library for file management
namespace file1
\
class !rogram
\
static void (ain(stringYZ args)
\
4ileStream fs Q ne2 4ileStream(M3y.t3tM&4ile(ode.,reate& 4ileccess.%rite)P
,onsole.%rite)ine(Menter file contents press Y4>Z to stopM)P
byte bP
2/ile (true)
\
bQ(byte),onsole.7ead()P

if (b QQ 255)
\
,onsole.%rite)ine(Mfile successfully created....M)P
,onsole.7eadJey()P
brea*P
]
else
\
fs.%rite+yte(b)P
]
]
fs.,lose()P
]
]
]
*inary/eader and *inary;riter Classes
$/e +inary7eader and +inary%riter classes are used to read from and 2rite to a binary
file. $/e +inary7eader class is used to read strings and elementary data types& suc/ as an
array& from a binary file& and t/e +inary%riter class is used to 2rite t/e elementary data
types in a file using t/e binary format.
?3
.xample4 input some c/aracters and to store t/e files. $/en display t/e content of file
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
using System.0BP
namespace file1
\
NNbinary reader V binary 2riter
class !rogram
\
static void (ain(stringYZ args)
\
string nameP
,onsole.%rite)ine(M#nter 4ile "ameM)P
nameQ,onsole.7ead)ine()P
4ileStream fs Q ne2 4ileStream(name& 4ile(ode.,reate& 4ileccess.7ead%rite)P
+inary%riter b2 Q ne2 +inary%riter(fs)P
+inary7eader br Q ne2 +inary7eader(fs)P

,onsole.%rite)ine(Menter file contentsM)P
int aP
2/ile (true)
\
aQ(int),onsole.7ead()P
if (a UQ-1)
\
b2.%rite((c/ar)a)P
]
else
\
,onsole.%rite)ine(Mfile successfully created....M)P
brea*P
]
]

fs.See*(8&See*Brigin.+egin )P
NNreading data from file
,onsole.%rite)ine(M4ile content is ...................M)P
int c/P
2/ile ((c/Qbr.7ead())UQ-1)
\
,onsole.%rite((c/ar)c/)P
]
br.,lose()P
,onsole.7eadJey()P
?4
]
]
]
0n t/e above e3ample& t/e see*() met/od is used to set t/e file pointer to t/e beginning of
t/e file.
S!ntax of see*()
2)inar!Reader ob'ect3-see:@offset> See:%rigin-ObeginBcurrentB.ndPA=
/ote: 4ffset is 5
The Strea&/eader and Strea&;riter
$o read from and 2rite c/aracters to t/e file& use Sream7eader and Stream%riter classes
defined in t/e System.0B namespace.
.xample4
$o input line of te3t and to store a file. $/en display file content
using SystemP
using System.,ollections.GenericP
using System.)in;P
using System.$e3tP
using System.0BP
namespace file1
\
NNbinary reader V bina7< 2riter
class !rogram
\
static void (ain(stringYZ args)
\
4ileStream fs Q ne2 4ileStream(MSr2$est1.t3tM& 4ile(ode.,reate&
4ileccess.7ead%rite)P
Stream%riter s2 Q ne2 Stream%riter(fs)P
Stream7eader sr Q ne2 Stream7eader(fs)P
,onsole.%rite)ine(Menter file contentsM)P
string aP
2/ile (true)
\
a Q ,onsole.7ead)ine()P
if (a QQ null)
\
?5
,onsole.%rite)ine(Mfile successfully created....M)P
brea*P ]
else
\
s2.%rite)ine(a)P
]
]
s2.4lus/()P
sr.+aseStream.See*(8&See*Brigin.+egin)P
NN or fs.See*(8& See*Brigin.+egin)P
NNreading data from file
,onsole.%rite)ine(M4ile content is ...................M)P

aQsr.7ead$o#nd()P

,onsole.%rite)ine(a)P

sr.,lose()P
,onsole.7eadJey()P
]
]
]
$/e &rite@ A and &riteLine@ A met/od used to 2rite c/aracter and a line of te3t to t/e
file.
$/e lush@ A met/od is used to force t/e immediate e3ecution of all t/e 2rite( ) and
2riteline( ) met/ods currently in t/e ;ueue.
$/e ReadTo.nd met/od is used to read t/e entire data from t/e file.
The Directory class

$o System.0B model also enables you to 2or* 2it/ derives and folders by using t/e
1irectory class. 0n ,-."#$ & t/e directory class /as multiple met/ods defined& to create&
edit& and delete folders& and to maintain drives on a computer.
,reate1irectory(pat/) $o create ne2 directory in t/e specified drive
1elete(pat/) $o delete t/e specified directory
#3ists(pat/) $o c/ec* t/e specified directory is already e3ists
Get1irectory7oot(pat/) $o get t/e root directory of t/e specified directory
Get)ogical1rives() 0t is used to get t/e names of t/e logical drives on
t/e current computer.
(ove(source&destin) 0t is used to move source directory(files) to
?>
destination directory
.xamples4 $o create a director
using System.0BP
namespace file1
\
class !rogram
\
static void (ain(stringYZ args)
\
Directory.CreateDirectory(1C:;Test*1)<
=
=
=
.xample 6 $o delete directory
using System.0BP
namespace file1
\
class !rogram
\
static void (ain(stringYZ args)
\
Directory.Delete(1C:;Test*1)<
Console./rite0ine('Directory created()<
Console.+ead,ey()<
=
=
=
.xample 6 $o c/ec* directory is e3ists &ot/er 2ise create ne2 directory
using System.0BP
namespace file1
\
class !rogram
\
static void (ain(stringYZ args)
\
if(1irectory.#3ists(1C:;Test*1))
>
Console./rite0ine(1Directory already e$ists1)<
=
else
?@
>
Directory.CreateDirectory(1C:;Test*1)
Console./rite0ine(1Directory created1)
=
Console.+ead,ey()<
=
=
=
.xample4 $o move file from specified directory to anot/er
using System.0BP
namespace file1
\
class !rogram
\
static void (ain(stringYZ args)
>
if(Directory.-$ists(1c:;test*1))<
>
Directory.)ove(1C:;test*1% 1C:;test31)<
=
else
>
Console./rite0ine(1Directory not moved1)<
=
Console.+ead,ey()<
=
=

.xample4 to display available logical drives in t/e system
using System.0BP
namespace file1
\
class !rogram
\
static void (ain(stringYZ args)
\int iP
StringYZ sQ ne2 stringY8ZP
s Q 1irectory.Get)ogical1rives()P
i Q s.)engt/P
,onsole.%rite)ine(M1isplay 1rive found in t/e systemM)P
for(int = Q 8P =SQi-1P=AA)
\
??
,onsole.%rite)ine(M1rive M A (= A 1) A M6 MA sY=Z)P
]
,onsole.7eadJey()P
]
]
]
5ultithreading in C4.!"T
(ultit/reading or free-t/reading is t/e ability of an operating system to concurrently run
programs t/at /ave been divided into subcomponents& or t/reads.
$ec/nically& multit/readed programming re;uires a multitas*ingNmultit/reading
operating system& suc/ as G"CN)inu3& %indo2s "$N2888 or BSN2P capable of running
many programs concurrently& and of course& programs /ave to be 2ritten in a special 2ay
in order to ta*e advantage of t/ese multitas*ing operating systems 2/ic/ appear to
function as multiple processors. 0n reality& t/e userKs sense of time is muc/ slo2er t/an
t/e processing speed of a computer& and multitas*ing appears to be simultaneous& even
t/oug/ only one tas* at a time can use a computer processing cycle.
multitas:ing operation system divides t/e available processor time among t/e
processes and t/reads t/at need it. t/read is e3ecuted in t/e given time slice& and t/en it
is suspended and e3ecution starts for ne3t t/readNprocess in t/e ;ueue. %/en t/e BS
s2itc/es from one t/read to anot/er& it saves t/read conte3t for preempted t/read and
loads t/e t/read conte3t for t/e t/read to e3ecute.
$/e lengt/ of time slice t/at is allocated for a t/read depends on t/e BS& t/e processor& as
also on t/e priority of t/e tas* itself.
0n ."#$ frame2or*& System.Threading namespace provides classes and interfaces
t/at enable multi-t/readed programming. $/is namespace provides6
ThreadPool class for managing group of t/reads&
Timer class to enable calling of delegates after a certain amount of time&
Mutex class for sync/roni5ing mutually e3clusive t/reads& along 2it/ classes
for sc/eduling t/e t/reads& sending 2ait notifications and deadloc* resolutions.
;o& to &or: threads> see the follo&ing example-
using SystemP
?D
using System.$/readingP
public class ServerClass
\
NN $/e met/od t/at 2ill be called 2/en t/e t/read is started.
public void 0nstance (et/od()
\
,onsole.%rite)ine(M<ou are in 0nstrance(et/od.7unning on $/read ^)P
,onsole.%rite)ine(M$/read Going to Sleep `5555555^)P
NN !ause for a moment to provide a delay to ma*e t/reads more apparent.
$/read. Sleep(3888)P
,onsole.%rite)ine (M<ou are +ac* in 0nstance(et/od.7unning on
$/read M)P
]
public static void Static(et/od()
\
,onsole.%rite)ine(M<ou are in Static(et/od. 7unning on $/read +.M)P
NN !ause for a moment to provide a delay to ma*e t/reads more apparent.
,onsole.%rite)ine(M$/read + Going to Sleep `5555555M)P
$/read.Sleep(5888)P
,onsole.%rite)ine(M<ou are bac* in static met/od. 7unning on $/read +M)P
]
]
public class Simple
\
public static int (ain(StringYZ args)
\
,onsole.%rite)ine (M$/read Simple SampleM)P
Server,lass serverBb=ect Q ne2 Server,lass()P
NN ,reate t/e t/read ob=ect& passing in t/e
NN serverBb=ect.0nstance(et/od met/od using a $/readStart delegate.
$/read 0nstance,aller Q ne2
$/read(ne2 $/readStart(serverBb=ect.0nstance(et/od))P
NN Start t/e t/read.
0nstance,aller.Start()P
,onsole.%rite)ine(M$/e (ain() t/read calls t/is M A
Mafter starting t/e ne2 0nstance,aller t/read.M)P
NN ,reate t/e t/read ob=ect& passing in t/e
NN serverBb=ect.Static(et/od met/od using a $/readStart delegate.
$/read Static,aller Q ne2 $/read(ne2
$/readStart(Server,lass.Static(et/od))P
NN Start t/e t/read.
Static,aller.Start()P
D8
,onsole.%rite)ine(M$/e (ain () t/read calls t/is M A
Mafter starting t/e ne2 Static,aller t/reads.M)P
return 8P
]
]
0f t/e code in t/is e3ample is compiled and e3ecuted& you 2ould notice /o2 processor time is
allocated bet2een t/e t2o met/od calls. 0f not for t/reading& you 2ould /ave to 2ait till t/e first
met/od slept for 3888 secs for t/e ne3t met/od to be called. $ry disabling t/reading in t/e above
code and notice /o2 t/ey 2or*. "evert/eless& e3ecution time for bot/ 2ould be t/e same.
n important property of t/is class (2/ic/ is also settable) is Priority-
Pausing and Resuming threads
fter you /ave started a t/read& you often 2ant to pause t/at t/read for a fi3ed period of
time. ,alling $/read.Sleep causes t/e current t/read to immediately bloc* for t/e number
of milliseconds you pass to "lee!& yielding t/e remainder of its time slice to anot/er
t/read. Bne t/read cannot call "lee! on anot/er t/read. ,alling
Thread."lee!(Timeout.Infinite) causes a t/read to sleep until it is interrupted by
anot/er t/read t/at calls $/read.0nterrupt or is aborted by $/read.bort.
fter a t/read /as started& you can c/ange t/e status of t/e t/read.
<ou can pause e3ecution of t/read some milliseconds& use Thread-sleep@A
met/od.
$o interrupt a t/read& you need to use Thread-interupt@A met/od
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIZZZZZZZZZIIIIIIIIIIIIIIII
Supplying para&eters to &ultithreaded procedures
/eturning #alues fro& &ultithreaded procedure
Creating ;indo's %or&s
user 0nterface is t/e means by 2/ic/ a user interacts 2it/ an application. data entry
screen t/at accepts input for products orders is an e3ample of a user interface.
D1
$/ere are t2o types of interfaces& c/aracter user interface(,C0) and Grap/ical user
0nterface(GC0). 0n ,C0 you interact 2it/ an application by entering commands (#g6 (S-
1BS).
GC0-based soft2are& on t/e ot/er /and& provide grap/ical interface for interacting 2it/
an application.#gP (S- 2indo2s& )inu'.
Visual ,-."et allo2s you to create console applications and 2indo2s-based application.
,onsole application provide a c/aracter user interface and 2indo2 based appliactions
provide a grap/ical user interface. 0n a 2indo2s-based appliaction& user interaction is
accomplis/ed 2it/ t/e /elp of 2indo2s forms and controls. 2indo2s form is t/e
main building bloc* on 2/ic/ you can design t/e user interface of a 2indo2s-based
application. ,ontrols are ob=ects t/at are placed on a form to allo2 a user to interact 2it/
an application.
*indo&s forms 4 2indo2s form is a representation on any 2indo2 displayed in an
application. 2indo2 form is used to accept input from a user and display information.
To create a &indo&/based application> 4irst open a 2indo2s application pro=ect" # File$
% new $% pro&ect $% choose 'isual C# ( select )indows $% then select )indows!orms*pplication
!rom the roghtt pane o! the Dialog window+ $% type your application name and location$% clic, o," )
"o2 display one form& and t/en design your o2n interface for an application.
#very 2indo2s forms /as various predefined properties& met/ods& and events associated
2it/ it. %indo2s properties are used to determine its appearance at run time. 2indo2s
form /as various properties& suc/ as si5e& bac*ground color& and position. Some
properties are given belo2.
Properties, Methods & Events of FORMS AND CONTROS
4orms and controls are t/e basic building bloc*s used to create t/e interfaceP t/ey are t/e
ob=ects t/at you 2ill 2or* 2it/ t/e build your application.
orms are ob'ects that expose
Properties 2/ic/ define t/eir appearance
Methods 2/ic/ define t/eir be/avior
.vents 2/ic/ define t/eir interaction 2it/ t/e user.
Control Properties 4,ontrols are ob=ects t/at are contained 2it/in form ob=ects.
,ontrols /as its o2n set of properties met/ods and events t/at ma*es it suitable for a
particular purpose.
D2
Some general Properties -! the control
.ame To specify the control name
/eight To specify the height of the control
)idth To specify the ,idth of the controls
Te0t To specify the caption.Title 4f the control
1ac,color To change the control bac+color
Forecolor To change the control forecolor( Text color
*ppearance Tto change the control appearance (6d.flat
Some general E'E.T o! the controls
Clic, To execute the program statements to user clic+ on the control
Dou2leClic
,
To execute the program statements to user 7oubleclic+ on the control
3otFocus To execute the program statements to user 84C9S the specified
control
4ostFocus To execute the program statements to user Mo:e control from the
control
5ouse5o6e To execute the program statements to user mo:e mouse pointer on the
control
5ouseDow
n
To execute the program statements to user mouse press on the control
5ouse7p To execute the program statements to user mouse release of the
control
8eyPress To execute the program statements to user press the +ey from the
+eyboard on of the control
((any more events are available
*indo&s orm .vents 6 n event is generated 2/en a user performs an action& suc/
as clic*ing t/e mouse or pressing a *ey. #ac/ form and controls /as a predefined set of
events associated 2it/ it. Some of t/e event associated 2it/ a 2indo2s form are listed
belo2.
Some %RM .vents
Clic, ; To execute the program statements to user clic+ on the 8orm
Dou2leClic
,
To execute the program statements to user 7oubleclic+ on the 8orm
*cti6ated To execute the program statements to acti:ate the form
Deacti6ate To execute the program statements to deacti:ate the form
4oad To execute the program statements to load form
5ousemo6e To execute the program statements to user mo:e mouse pointer on
the 8orm
D3
5ousedown To execute the program statements to user mouse press on the 8orm
8eypress To execute the program statements to user press the +ey from the
*eyboard on of t/e from
((any more events are available )
To Pa!"e CONTRO E#ENTS into the Code Page
<ou 2ant to place default event ( ,lic*) of t/e control into t/e code page& its very simple&
you double clic* on t/e control t/en move cursor to code page and place t/e ,)0,J
event procedure in to t/e code page as t/e follo2ing form ( you use same met/od to
ot/er controls)
The Weneral form of the control .vents-
pri6ate 6oid control9E6ent#ob2ect sender1 $:entArgs e+
:
;;;;;;;;;"
Statements"
<
or example><ou place a button control on t/e form and you 2ant to clic* on t/e button
at t/e runtime to display one message. $/is is done by t2o 2ays.
4irst double clic* on t/e button t/en automatically add ,)0,J event procedure into t/e
code page and use Message)ox-Sho&@A funtion to display message on t/e message
2indo2
Synta36
5essage1o0"Show#=message=,=caption=,5essage1o01uttons,5essager1o0>con+
Eg:
5essage*o9.Sho'=G;elco&e to &ictG1 G5ictG1 5essage*o9*uttons.2H1
5essage*o9Icon.Infor&ation>A
Example:
Bpen one <indo,sformsApplication and place one =utton control on t/e form. $/en
2rite t/e follo2ing code into t/e form code 2indo2.
!rivate void button*?Clic@(obAect sender% -vent.rgs e)
>
)essageBo$."ho&(1/elcome to mict1% 1)ict1% )essageBo$Buttons.B,%
)essageBo$Icon.Information)<
=
D4
E6ent 7escription
Clic, This e:ent occurs ,hen a user clic+s any,here on a ,indo,s from(
Closed This e:ent occurs ,hen a form is closed
Deacti6ate The e:ent occurs ,hen a form loses focus and is no longer the acti:e
form(
4oad This e:ent occurs ,hen a form is loaded in the memory for the first
time( >t can be used to initiali-e :ariables and any other statements
execute at the time of form load(
5ouse5o6e This e:ent occurs ,hen a mouse mo:e o:er the form
5ouseDow
n
This e:ent occurs ,hen a mouse left button is pressed on a form
5ouse7p This e:ent occurs ,hen the mouse button is released(
Some *indo&s orm Methods as given belo&
Sho&@ A Csed to display a form
Dim frmob' as ne& orm5
rmob'-Sho&@A
Activate @A $o set t/e focus in a form
rm%b'-Activate@A
Close @A $o clase t/e form
rm%b'-Close@A
SetDes:topLocatio
n
$o set t/e des*toploaction of t/e form at run time
rm%b'-setDes:topLocation@6XX>7XXA
Creating &indo&s form4
<ou can use controls to define an interface. 0n ,-."#$& different types of controls are
available. .ust drag and drop controls into t/e form to design an interface for an
application. 0n ,-."#$ generally used controls as given belo2
*indo&s Controls
5- Label Control
)abel control is a grap/ic control you can use to display te3t t/at a user canFt c/ange
directly.
6- Text )ox control
$e3t+o3 control& sometimes called an edit field or edit control& displays information
entered at design& entered by t/e user& or assigned to t/e control in code at run time.
7- )utton Control
Cse a button control to begin& interrupt& or end a process. %/en c/osen a button appears
pus/ed in and so is sometimes called pus/ button. $o display te3t on a button& set t/e
Text property.
D5
8- Wroup)ox Control
Group+o3 control provides an identifiable grouping for controls. <ou can also use a
Group+o3 to subdivide a form functionality. 4or e3ample& to separate groups of
Bption+uttonNc/ec* bo3 controls.
J- Panel Controls
$/e panel control is similar to t/e Group+o3. 0t allo2s you to group related items
toget/er. !anel controls provide scrollbars and does not /ave a caption& 2/ereas
groupbo3 does not /ave a scrollbar.
[ ,ro#ide e9a&ple of controls ]
K- Radio )utton control
n 7adiobutton control displays an option t/at can be turned on or off. Csually
7adiobutton controls are used in an option group to display options from 2/ic/ t/e user
selects only one.
M- Chec:)ox Control
c/ec* bo3 control display as 2/en selected. $/e disappears 2/en t/e c/ec* bo3 is
cleared. <ou can use c/ec*bo3 controls in groups to display multiple c/oices from
2/ic/ t/e user can select one or more
N- List)ox Control
)ist+o3 control displays a list of items from 2/ic/ t/e user can select one or more. 0f
t/e number of items e3ceeds t/e number t/at can be displayed& a scroll bar is
automatically added to t/e )ist+o3 control.
[- chec:edlistbox control
$/is control /as t/e same functionality as t/e )ist+o3 control. 0n adition& t/e
,/ec*ed)ist+o3 control displays a c/ec* bo3 ne3t to t/e items in t/e list.
5X- Lin:Label4
1isplay a )in*lable controls t/at support /yperlin* functionality& formatting& and
trac*ing. %/en you clic* t/e lin*& it open anot/er form or 2ebsite.
55- Combo )ox4
combo bo3 control combines t/e features of a $e3tbo3 and a )ist bo3 control- users
can enter information in t/e te3t bo3 portion or selection item from t/e list bo3 portion of
t/e control.
56- Picture )ox Control-
D>
!icture+o3 control can display a grap/ic from a bitmap& icon& or metafile& as 2ell as
en/anced metafile& .!#G&G04 files. $o ma*e !icture+o3 control automatically resi5e to
display an entire grap/ic& set its Si5e(ode property. $o create animation or simulation&
you can manipulate grap/ics properties and met/ods in code. $o load a picture in
!icture+o3 & use 0mage property 2it/ S!stem-Dra&ing-)itmap@filepathA function
.g4 Picturebox5-imageIne& Dra&ing-)itmap@QC4GimagesGfish-'pgRA
57- Scroll)ar controls
Scroll +ars provide easy navigation t/roug/ a long list of items or a large amount of
information. $o type scrollbars available& ;scrollbar and <scrollbar-
58- Timer Control
$imer control can e3ecute code at regular intervals by causing a $imer event to occur.
$/e $imer control& invisible to t/e user& is useful for bac*ground processing.
5J- Numeric+pDa&n controls
n Cp1a2n control /as a pair of arro2 buttons 2/ic/ t/e user can clic* to increment or
decrement a Value& suc/ as a scroll position or a value in an associated control *no2n as
a buddy control. $o get t/e value of t/e control use <alue property.
5K- DateTimePic:er Control
$/is control allo2s a user to select a sigle item from a list of dates times. $o set t/e
minimum and ma3imum dates in t/e control by using mindate and maxdate property.
$o get t/e seleted date from t/e control by use <alue property
5M- Progress)ar Controls
$/e !rogress+ar controls s/o2s t/e progress of a lengt/y operation by filing a rectangle
2it/ c/un*s from left to rig/t. progressbar control /as a range and a current position.
5N- Trac:)ar Controls
trac*bar control is a 2indo2 containing a trac* and optional tic* mar*s. $o set t/e
minimum and maimum value of t/e control& use Minimum and Maximum property.
nd c/ange tic* values& use Tic:re0uenc! property.
5[- List<ie& Control
$/is control displays a list of items along 2it/ icons. <ou can use it along 2it/ t/e
$reeVie2 control to create as interface similar to t/at of 2indo2s e3plorer((y computer)
. $o add items in t/e listvie2 control by using items property
$/e commonly used properties are6
(utiselect : multiple items can be select
,/ec*bo3es : display c/ec*bo3es ne3t to list items
D@
)arge0magelist : to get or set t/e currently set imagelist for large icon mode.
Samall0magelist - to get or set t/e currently set imagelist for small icon mode.
6X- lo&La!outPanel Control
Handles t/e layout of its components and arrange t/em in a flo2 layout automatically. 0t
is mainly used to arrange t/e its components automatically at t/e time of resi5ing t/e
control.
65- "magelist control
(anages of a collection of images t/at are typically used by t/e ot/er controls suc/ as
listVie2& $reeVie2& or $oolStrip.
66- Mas:edText)ox
Cse a mas* to distinguis/ bet2een proper and improper user input. 0tFs t/e better control
for /andling date input. 0ts provide mas*ed te3t to input data format& to set mas* of data
by using mas: property to get t/e data from t/e control& use Text property
67- RichText)ox Control
!rovides advanced te3t entry and editing features suc/ as c/aracter and paragrap/
formatting 0t is default multiline entry control and its provide many function to apply
different format at t/e selected portion of t/e te3t& and save t/e contents as file.
68- StatusStrip Controls
statusstrip control provides a 2indo2& usually at t/e bottom of a parent form& t/roug/
2/ic/ an application can display various *inds of status data and provide various buttons
suc/ as statuslable& progressbar & dropdo2n list and splitbutton&
6J- ToolStrip Controls
$/e $oolstrip similar to t/e toolbar& a $oostrip control provides a 2indo2& usually at t/e
top of a parent form& t/roug/ 2/ic/ an application can display various *inds of controls
suc/ as lablel& button& splitbutton& te3tbo3& progressbar & and dropdo2n list
6K- Tree<ie& Control
$reeVie2 control displays a /ierarc/ical list of "ode ob=ects& eac/ of 2/ic/ consists of
a label and an optional bitmap. treevie2 is typically used to display t/e /eadings in a
document t/e entries in an inde3& t/e files and directories on a dis*& or any ot/er *ind of
information t/at mig/t usefully be displayed as a /ierarc/y. #ac/ node may contain
ot/er nodes. Suc/ a node called t/e parent node and t/e contained nodes are called
c/illed nodes. n ob=ect of t/e TreeNode class represents eac/ node in t/e treevie2
control. <ou can add ne2 nodes to a treevie2 control by using t/e add@A met/od of t/e
nodes collection.
7im ne,node as ne, Tree/ode(?Parent /ode@
Tree:ie,%(nodes(add(ne,node
D?
Tree:ie,%(Selected/odeAne,node
7im childnode as ne, Treenode(?Chiled /ode@
Tree:ie,%(Selected/ode(/odes(Add(Chilednode
6M- TabStrip Controls
$abStrip control is li*e t/e dividers in a noteboo* or t/e labels on a group of file
folders. +y using a $abStrip control& you can define multiple pages for t/e same area of a
2indo2 or dialog bo3 in your application. $/e control consists of one or more $ab
ob=ects in a $abs collection. t bot/ design time and run time.
6N- *eb )ro&ser control
0t is used to display any 2eb page in side t/e form.(it is an internet e3plorer component).
6[- SplitContainer control
1ivides a containerFs display area into t2o resi5able panels to 2/ic/ you can add controls
7X- Splitter control
1ivides a containerFs display area into t2o areas 2/ic/ you can be resi5ed
75- Menu Control
menu control displays a custom menu for your applications. menu can include
commands& submenus& and separator bars. $o create a (enu ,ontrol& use t/e (enu
#ditor ( $ools (enu -T (enu #ditor). #nter t/e name of t/e (enu control in t/e ,aption
+o3. $o create a separator bar& enter a single /yp/en(-) in t/e ,aption +o3. $o display a
c/ec* mar* to t/e left of a menu item& select t/e ,/ec*ed bo3.
[ ,ro#ide e9a&ple of a-o#e descri-ed controls ]
;indo's Co&&on dialog controls
$/e (S-%indo2s Bperating system provides commonly used 2indo2s 1ialog bo3es
suc/ as Bpen& Save& Save s & !rint 1ialog bo3es. $o use t/e open dialog bo3 to open a
file and display its contents& you need to use t/e in/erited classes of t/e CommonDialog
class.
0n ,-."#$& t/e ,ommon1ialog class is t/e base class for displaying common dialog
bo3es& suc/ as t/e color& font and t/e file dialog bo3es
$/e classes t/at are in/erited from t/e ,ommon1ialog class are ,olor1ialog&
4ont1ialog& 4ile1ialog& !rint1ialog& and !ageSetup1ialog. ll t/ese classes also /ave
corresponding controls t/at you can add to a form from t/e Tool)ox
ColorDialog Classes
DD
$o c/ange t/e bac*ground and t/e foregraound color of te3t& you can use t/e default
Color dialog bo3. $o use t/e default ,olor dialog bo3& you can eit/er add a ,olor1ialog
control to t/e form or create an instance of t/e in/erited ,olor1ialog ,lass.
.g4 $o invo*e color1ialog
$o place a $e3tbo3 and a button into t/e form & t/en 2rite t/e follo2ing code
namespace %indo2s4ormspplication1
\
public partial class 4orm5 6 4orm
\
,olor1ialog , Q ne2 ,olor1ialog()P
public 4orm5()
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
if (,.S/o21ialog() QQ 1ialog7esult.BJ)
\
te3t+o31.+ac*,olor Q ,.,olorP
]
]
]
]
ontDialog Class
<ou can use t/e default ont dialog bo3 to c/ange t/e font& font style& and si5e of te3t.
$o use t/e default 4ont dialog bo3& you can eit/er add a 4ont1ialog control to t/e form or
create an instance of t/e in/erited 4ont1ialog ,lass.
.g4 $o invo*e 4ont1ialog
$o place a $e3tbo3 and a button into t/e form & t/en 2rite t/e follo2ing code
namespace %indo2s4ormspplication1
\
public partial class 4orm5 6 4orm
\
4ont1ialog fd Q ne2 4ont1ialog()P
public 4orm5()
\
0nitiali5e,omponent()P
]
188
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
if (fd.S/o21ialog() QQ 1ialog7esult.BJ)
\
te3t+o31.4ont Q fd.4ontP
]
]
]
]
ileDialog Class
$/e 4ile1ialog class is an abstract class t/at is in/erited from t/e ,ommon1ialog ,lass.
$/e 4ile1ialog class cannot instatiate. <ou can use t/e Bpen4ile1ialog or
Save4ile1ialog class to open a file from or save a file to t/e dis*.
%penileDialog class
<ou 2ant to invo*e t/e default %pen dialog bo3 to open a filPe in t/e ,-."#$
environment& you eit/er need to add an Bpen4ile1ialog control to t/e form or instantiate
t/e Bpen4ile1ialog class.
.g4 $o invo*e Bpen4ile1ialog
$o place a 7itc/$e3t+o3 and a button into t/e form & t/en 2rite t/e follo2ing code
namespace %indo2s4ormspplication1
\
public partial class 4orm5 6 4orm
\
Bpen4ile1ialog opd Q ne2 Bpen4ile1ialog()P
public 4orm5()
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
if (opd.S/o21ialog() QQ 1ialog7esult.BJ)
\
string e3tP
e3t Q opd.4ile"ame.Substring(opd.4ile"ame.)engt/ - 3& 3).$oCpper()P
if (e3t.#;uals(M$'$M))
ric/$e3t+o31.)oad4ile(opd.4ile"ame&
7ic/$e3t+o3Stream$ype.!lain$e3t)P
else if (e3t.#;uals(M7$4M))
ric/$e3t+o31.)oad4ile(opd.4ile"ame&
181
7ic/$e3t+o3Stream$ype.7ic/$e3t)P
else
(essage+o3.S/o2(M4ile $ype is not validM& M#rrorM
&(essage+o3+uttons.BJ&(essage+o30con.#rror)P
]
]
]
]
SaveileDialog Class
<ou 2ant to invo*e t/e default Save As dialog bo3 to over2rite an e3isting file or create
a ne2 file. 0n ,-."#$ environment& you eit/er need to add an Save4ile1ialog control to
t/e form or instantiate t/e Save4ile1ialog class.
.g4 $o invo*e Save 4iledialog
$o place a $e3tbo3 and a button into t/e form & t/en 2rite t/e follo2ing code
namespace %indo2s4ormspplication1
\
public partial class 4orm5 6 4orm
\
Save4ile1ialog sfd Q ne2 Save4ile1ialog()P
public 4orm5()
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
if (sfd.S/o21ialog() QQ 1ialog7esult.BJ)
\
ric/$e3t+o31.Save4ile(sfd.4ile"ame&
7ic/$e3t+o3Stream$ype.7ic/$e3t)P
(essage+o3.S/o2(M4ile successfully savedM& M(essageM&
(essage+o3+uttons.BJ&(essage+o30con.0nformation)P
]
]
]
]
PrintDialog Class
182
0n t/e ,-."#$ environment& you can use t/e default !rint dialog bo3 to print any te3t or
grap/ics. $o invo*e t/e default print dialog bo3& you need to eit/er add a !rint1ialog
control and a !rint1ocument control to t/e form or create an instance of t/e !rint1ialog
classes.
#g6 0nvo*e print1ialog and print a file
$o place a $e3tbo3 and t2o buttons into t/e form ( one for open file and ot/er as print) &
t/en 2rite t/e follo2ing code
PrintPrevie&Dialog class
$o invo*e default !rint!revie2 dalog bo3 to display t/e document as printed format in
t/e control. <ou need to eit/er add a !rint!revie21ilog control to t/e form or create an
instance of t/e !rint!revie21ialog ,lasses or <ou can also need to create your o2n
printprevie2 2indo2& use !rint!revie2,ontrol& =ust drag !rint!revie2,ontrol control
into t/e form and set t/e 2/ic/ document you 2ant display t/e control.
Print ( PrintPrevie&
$o open a file into t/e 7ic/$e3t+o3 ,ontrol and clic* on t/e !rint button.
$o place a !rint1ocument ,ontrol and c/ange t/e names as ^pdc_
$o create an ob=ect of !rint1ialog class& named as ^pd_
private void !rint+utton[,lic*(ob=ect sender& #ventrgs e)
\
!rinterSettings pntr Q ne2 !rinterSettings()P
pd.!rinterSettings Q pntrP
if (fname UQ MM)
\
if (pd.S/o21ialog() QQ 1ialog7esult.BJ)
\
pdc.1ocument"ame Q fnameP
pd.1ocument Q pdcP
pdc.!rint()P
]
]
]
private void pdc[!rint!age(ob=ect sender& !rint!age#ventrgs e)
\
183
int / Q pdc.1efault!ageSettings.!aperSi5e.Heig/tP
int t Q pdc.1efault!ageSettings.(argins.$opP
int b Q pdc.1efault!ageSettings.(argins.+ottomP
int int!rintreaHeig/t Q / - t - bP
int 2 Q pdc.1efault!ageSettings.!aperSi5e.%idt/P
int l Q pdc.1efault!ageSettings.(argins.)eftP
int r Q pdc.1efault!ageSettings.(argins.7ig/tP
int int!rintrea%idt/ Q 2 - l - rP
int margin)eft Q pdc.1efault!ageSettings.(argins.)eftP
int margin$op Q pdc.1efault!ageSettings.(argins.$opP
e.Grap/ics.(easureString(ric/$e3t+o31.$e3t& ric/$e3t+o31.4ont)P
7ectangle4 rect!rintingrea Q ne2 7ectangle4(margin)eft& margin$op&
int!rintrea%idt/& int!rintreaHeig/t)P
e.Grap/ics.1ra2String(ric/$e3t+o31.$e3t& ric/$e3t+o31.4ont&
+rus/es.+lac*& rect!rintingrea& ne2
String4ormat(String4ormat4lags.)ine)imit))P
]

private void !revie2+utton[,lic*(ob=ect sender& #ventrgs e)
\
print!revie21ialog1.1ocument Q pdcP
print!revie21ialog1.S/o21ialog()P
]
PageSetupDialog class
$o invo*e default pagesetup dalog bo3 to set t/e page details for ptinting in 2indo2s
appliaction& you need to eit/er add a !ageSetup1ialog control to t/e form or create an
instance of t/e !ageSetup1ialog ,lasses. <ou can also need to create instance of t/e
!ageSettings class. $/e !ageSettings class is include in t/e System.1ra2ing.!rinting
namesapce& and it is used to specifiy t/e settings to be applied to every printer page.
.g4 $to invo*e page setup dialog and print a file
$o open a file into t/e 7ic/$e3t+o3 ,ontrol and clic* on t/e !rint button.
$o create an ob=ect of !rint1ocument class& named as ^pdc_
$o create an ob=ect of !rint1ialog class& named as ^pd_
$o create an ob=ect of !ageSettings class& named as ^ps_
private void pageSetup+utton[,lic*(ob=ect sender& #ventrgs e)
\
184
psd.!ageSettings Q psP
if (psd.S/o21ialog() QQ 1ialog7esult.BJ)
\
pdc.1efault!ageSettings Q psd.!ageSettingsP

]
]
3ser Controls
<ou can create custom control for build your applications& t/sat is done by creating a
control library. ,ontrol libraries are similar to t/e class library. control library 2ill
compile to its o2n assembly& 2/ic/ you can use in your appliaction. $/is met/od is
attractive& because it means you can distribute t/e assembly to ot/er developers 2it/ out
giving a2ay your source code. <ou can c/anges to t/e assembly& and t/ese 2ill be reflect
in t/e applications t/at use it.
Bpen a ne2 user control pro=ect& named as ^$est,ontrol_
1. $/en create t/e user control as t/e follo2ing format
%rite t/e follo2ing code into t/e code page
namespace %indo2s4ormspplication1
\
public partial class 4orm5 6 4orm
\
float si%amt%!r%ra<
public 4orm5()
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
if (sfd.S/o21ialog() QQ 1ialog7esult.BJ)
185
\
ric/$e3t+o31.Save4ile(sfd.4ile"ame&
7ic/$e3t+o3Stream$ype.7ic/$e3t)P
(essage+o3.S/o2(M4ile successfully savedM& M(essageM&
(essage+o3+uttons.BJ&(essage+o30con.0nformation)P
]
]
]
]
namespace %indo2s4orms,ontrol)ibrary1
\
public partial class Cser,ontrol1 6 Cser,ontrol
\
float si& amt& pr& raP
public Cser,ontrol1()
\
0nitiali5e,omponent()P
]
public void GetValues()
\
amt Qfloat.!arse (te3t+o31.$e3t)P
pr Q float.!arse (te3t+o32.$e3t)P
ra Q float.!arse (te3t+o33.$e3t)P
]

public float get0nterest
\
get
\
si Q amt O pr O (ra N 188)P
return siP
]
]

]
]
2. Save t/e pro=ect and build testlibrary pro=ect.
3. $/en close t/e pro=ect and open a ne2 2indo2s from application.
4. 0n t/e 2indo2s form & first you 2ant to place ytour user ciontrol on to t/e toolbo3&
select toolbo3 andf rig/t cli*& select choose items option from t/e conte3t menu
18>
5. $/en select bro2se tab and point debug directory from t/e testcontrol pro=ect
directory
>. $/en select your TestControl-DLL file& clic* o*
@. nd clic* V drag on t/e form to place user control& and place one te3t bo3 to
display result and provide one button.
?. $/en 2rite t/e follo2ing code and e3ecute your program
namespace %indo2s4ormspplication1
\
public partial class 4orm1 6 4orm
\
public 4orm1()
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
user,ontrol11.GetValues()P
te3t+o31.$e3t Q user,ontrol11.get0nterest.$oString()P
]
]
]
Data-ase Connections in C4.!"T
AD%-N.T4 0n todayFs 2orld& business applications need to manage data. 1ata is
generally stored in a relational database in t/e form of related tables. 7etriving and
manipulating data directly from a database re;uires t/e *no2ledge of database
commands to access t/e data. 4or e3ample& updating t/e data stored in a (icrosoft S9)
Server database may not be convenient for a person 2/o does not *no2 S9) statements.
(ost business applications allo2 users to retrieve t/e data stored in a database and
present it in a user-friendly interface 2it/out /aving to 2rite database commands. $/e
user can even add&delete& and update database records directly from applications.
pplication need to communicate 2it/ a database for t/e follo2ing tas*s6
5- 7etrieving t/e data stored in t/e database and presenting itin a user-friendly
format.
6- Cpdating t/e database& t/at is& inserting& modifying& and deleteting data.
18@
*D-".ET is a model used by (/$T applications to communicate ,ith a database for
retrie:ing1 accessing1 and updating data(
Fetaures o! *D-".ET
1. Disconnected data Architecture 4 1B."#$ uses t/e disconnected data arc/itecture.
pplications connect to t/e database only 2/ile retrieving and updating data.fter data
is retrieved& t/e connection 2it/ t/e database is closed. %/en t/e database needs to be
updated& t/e connection is re-establis/ed.
2. Data cached in datasets 4 dataset is t/e most common met/od of accessing data
sine it implements a disconnected arc/itecture. Since 1B."#$ is based on a
disconnected data structure& it is not possible for t/e application to interact 2it/ t/e
database for processing eac/ record.$/erefore& t/e data is retrieved and stored in
datasets. dataset is a cac/ed set of database records.
3. Data Transfer in 9ML format4 '() is t/e fundamental format for data transfer in
1B."#$. 1ata is transferred from a database into a dataset and from t/e dataset to
anot/er component by using '().<ou can even use an '() file as a data source and
store data from it in a dataset. '() is an industry standard format for e3c/anging
information bet2een different types of applications.$/e *no2ledge of '() is not
re;uired for 2or*ing 2it/ 1B."#$ since data conversion from and to '() is /idden
from t/e user.
4. "nteraction &ith the database is done through data commands4 ll operations on
t/e database are performed by using data commands. data command can be a S9)
statement or a stored procedure. <ou can retrieve& insert& delete& or modify data from a
databse by e3ecuting data commands.
The AD%-N.T ob'ect Model
1B."#$ uses a structured process flo2 containing componenets. $/e structured
process flo2 or t/e ob=ect model is s/oen in t/e follo2ing figure6
18?
+ign a Dataset 4 $/e data is cac/ed in a dataset and t/e application accesses t/e
data from t/e dataset.
+sing a Data Reader 4 $/e 1ata7eader ob=ect& 2/ic/ is a component of t/e data
provider&uses t/e ,onnection ob=ect to connect to t/e database& uses t/e ,ommand
ob=ect to retrieve data& and provides data to t/e application in a read-only and
for2ard-only mode
Data Provider
1ata !rovider is used for connecting to a database& retrieving data& storing data in a
dataset& reading t/e retrieved data& and updating t/e database.
$/ere are t/ree types of data providers.
1. %L.D) Provider4 $/is type of data provider 2or*s 2it/ all t/e B)# 1+
providers& suc/ as S9) B)#1+ provider& Bracle B)#1+ !rovider& and .#$N,#
B)#1+ provider. $/e B)#1+ data provider classes are present in t/e
S!stem-Data-%ledb namespace.
6- %D)C data provider4 0t is an open source data base connectivity. ((S1S9)) . n B1+, data
source can be accessed t/roug/ 1B."#$ by using t/e B1+,."#$ provider. $/e
implementation of t/e B1+,."#$ data provider is t/e same as t/at of t/e B)#1+ data provider
and S9) Server data provider. (S!stem-Data-%D)C namesapce).
7- S1L Server data provider4 $/is type of data provider is used to 2or*
specifically 2it/ (S-S9) server. S9) Server data provider is recommended
for 2or*ing 2it/ (S-S9) server data source& since a S9) server data provider
18D
allo2s fast access to a data source 2it/out going t/roug/ an B)#1+ or B1+,
layer. $/e S9) Server data provider classes are present in t/e
System"Data"SqlClient namesapce.
3sing DataAdapter and DataS"T
Data Adapter
data dapter is integral to t/e 2or*ing of 1B."#$ since data is transferred to and
from a database t/roug/ a data adapter. data dapter retrieves data from a database
into a dataset and updates t/e database. %/en you ma*e c/anges to t/e dataset& t/e
c/anges in t/e database are actually done by t/e data adapter. $/e data adapter first
compares t/e data in t/e dataset 2it/ t/at in t/e database and t/en updates t/e database.
<ou connect to a database by configuring a data adapter. $/ree types of data adapter are
used6
S0lDataAdapter4 0t is used to configured to access data specifically from (S-
S9) Server
%D)CDataAdapter4 0t is used to configured to access data from any database
suc/ as (S-,,#SS&(S-S9) ServerIetc
%L.D)DataAdapter 4 0t is used to configured to access data from any database
t/at is suppoerted by an B)#1+ data provider.
data adapter /andles data transfer bet2een t/e database and t/e dataset t/roug/ its
properties and met/ods and displays t/e data t/roug/ t/e process of table mapping.
Data Adapter Properties and Methods
data adapter communicates 2it/ a databse 2/ile retrieving& inserting& deleting& and
updating data.
Select Command 7efers to a S9) statement or a stored procedure ro retrive data
from t/e database
"nsertCommand 7efers to a data command to insert data into a database
+pdateCommand 7efers to a data command to update a database
DeleteCommand 7efrs to a data command to delete data from a database
ill@ A met/od 4ills t/e dataset 2it/ t/e records from a database
+pdate@ A met/od #3ecute t/e corresponding 0nsert,ommand& Cpdate,ommand or
1elete,ommand for eac/ inserted& modified& or deleted ro2
to refelect t/e c/anges in t/e database.
DataS.T
118
$/e 1ataSet components is a cac/e of data t/at is stored in memory. 0tFs a lot li*e a mini
database engine& but its data e3ists in memory. Since t/e dataset component stores all of
t/e data in memory& you can scroll t/roug/ t/e data bot/ for2ard and bac*2ard& and can
also ma*e updates to t/e data in memory.
$/e 1ataSet is a disconnected& cac/ed set of records t/at are retrieved from a database.
%/en a connection is establis/ed 2it/ t/e database& t/e 1atadapter creates a dataset
and stores data in it. fter t/e data is retrieved and stored in a dataset& t/e connection
2it/ t/e database is closed.
Data )indings
1ata bindings means ta*ing data referenced by your +indingSource and binding it to a
control. 0n ot/er 2ords& t/e control 2ill receive its data from your data access
components& and t/e data 2ill be automatically displayed in t/e control for t/e user to
see and manipulate.
.xample6 to display all student details into t/e 1ataGridVie2 control.
$/e DataWrid<ie& control is used to display records 2it/ t/e form of spreads/eet (including
ro2 and column format). 0n t/is control& data can be directly edit and updating to t/e database.
$o display records in t/is control& use DataAdapter and DataSet ob=ects
Im!orts "ystem.Data.BleDb
Public Class 8orm*
Dim CB44 .s 4e&
BleDbConnection(1Provider2)icrosoft.Cet.B0-DB.D.3<Data
"ource2C:;Documents and "ettings;mict?.)ICTE,)F);)y
Documents;"tudent.mdb1)
Dim D.da!ter .s 4e& BleDbData.da!ter
9create data.da!ter obAect
Dim D"et .s 4e& Data"et 9create dataset obAect
111
Dim st .s "tring
Private "ub Button*?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles Button*.Clic@
If CB44."tate 2 3 Then CB44.Close()
CB44.B!en()
D.da!ter."electCommand 2 4e& BleDb.BleDbCommand
D.da!ter."electCommand.Connection 2 CB44
D.da!ter."electCommand.CommandTe$t21select H from stud1
D"et 2 4e& Data"et
D.da!ter.8ill(D"et% 1stud1)
DataFrid:ie&*.Data"ource 2 D"et.Tables(1stud1)
CB44.Close()
-nd "ub
Private "ub Button?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles Button.Clic@
)e.Close()
-nd "ub
-nd Class
3sing *indingSource and *inding !a#igator
)indingSource control 4 $/e +indingSource component acts li*e a bridge bet2een
your data source(1ataSet) and your data-bound controls(t/at is& controls t/at are bound
to data components). ny interaction 2it/ t/e data from your controls goes t/roug/ t/e
+indingSource component& 2/ic/ in turn communicates 2it/ your data source.
0t is used to set t/e data source of t/e 1ataset and 1atadapter control and provides
navigation& filtering& sorting and updating capabilities.
)indingNavigator control 4 $/e +inding"avigator component provides a statndard
C0 component t/at allo2s you to navigate t/roug/ t/e records t/at are in your data
source. $/is componet is bound to your +indingSource component. %/en you clic* t/e
"e3t button in t/e +inding"avigator component& it in turn sends are;uest to t/e
+indingSource component for t/e ne3t record& and t/e +inding source component in turn
sends t/e re;uest to t/e datasource.
.xample as given belo& 4 Csing )indingSource and )indingNavigator controls to
manage student details.
112
Select +inding"avigator1 control and c/ange t/e Doc: property is none
To connect database to the control > do the follo&ing steps
1. $o !lace a +indingSource ,ontrol into t/e form
2. Select )indingSource5 ,ontrol and ,lic* on t/e dataSource property.
3. Bne 1ialog bo3 appears& ,lic* Add Pro'ect Data Source option
4. 1ata Source ,onnection 1ialog bo3 appears& ,/oose Database 0con and clic* "e3t
button.
5. $/en clic* Ne& connection button& t/en display dd connection 1ialog bo3 appears ,lic*
Change button and select Microsoft Access database 8ile provider and clic* BJ&
>. $/en clic* )ro&se button and select your database file and clic* B*
@. Select yes button and display table 1ialog bo3& clic* (A) sign of t/e table and c/oose table
name
?. ,lic* inish button. "o2 create 1ataSet control into t/e form.
D. Select +indingSource1 control and c/oose 1ata(ember !roperty and c/oose $able name
18. "o2 create $able adapter control into t/e from.
11. Select +inding"avigator1 control and c/oose t/e property )indingSource and select your
+inding Source name.
12. $/en Select Text)ox5 control and clic* (A) sign of 1ata+indings property to e3pand t/e
properties tag and text
13. ,lic* Text property& dialogbo3 appears& clic* (A) sign of +indingSource1& e3pand t/e field
list and select 4ield name to assign into t/e $e3tbo31.
14. (,ontinue t/e step 13 to assign all field to t/e appropriate te3tbo3es)
15. $/en run t/e program and use +inding "avigator to navigate t/e records.
113
.xample 4 $o navigate t/e records& using +uttons& and delete t/e active record
$o continue t/e bove programFs database connection step (1 to 15)
Im!orts "ystem.Data.BleDb
Public Class 8orm*
Private "ub Button*?Clic@?*(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles Button*.Clic@
)e.Close()
-nd "ub
Private "ub btn8irst?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles btn8irst.Clic@
Binding"ource*.Position 2 3
-nd "ub
Private "ub btn4e$t?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles btn4e$t.Clic@
Binding"ource*.Position 62 *
-nd "ub
Private "ub btn!revious?Clic@(By:al sender .s
"ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles btn!revious.Clic@
Binding"ource*.Position E2 *
-nd "ub
Private "ub Btnlast?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles Btnlast.Clic@
114
Binding"ource*.Position 2 Binding"ource*.Count E *
-nd "ub
Private "ub btn+emove?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles btn+emove.Clic@
Binding"ource*.+emove.t(Binding"ource*.Position)
)sgBo$(1+ecord has been deleted ....1%)sgBo$"tyle.Information
6
)sgBo$"tyle.B@Bnly)
-nd "ub
-nd Class
%iltering and Sorting Data
Sometimes& you need not display all t/e retrieved records. 0n suc/ cases& you filter t/e
data so as to display only t/e desired records. 0n addition& you can sort t/e data to display
it in ascending or descending order of a particular column.
$/ere are t2o met/ods for displaying filtered data
1. ,reating parameteri5ed ;ueries.
2. 4iltering a dataset
Creating Parameteri#ed 1ueries
+y using parameteri5ed ;ueries& data can be filtered based on t/e criterion entered by a
user at run time. !arameteri5ed ;ueries are created 2/ile configuring data adapters or
specify S9) command into t/e code module.
n S9) 1ata dapter& t/e synta3 for t/e parameteri5ed ;uery 2ill be as follo2s
S.L.CT id> name> age sex>dob from stud &here@dobI\paramA
1irect apply commands to t/e command ob=ect& using follo2ing form
S.L.CT id> name> age sex>dob from stud &here dobI]date]
iltering DataS.T
fter data is retrieved in a dataset& you can filter t/e data stored in t/e dataset to vie2
customi5ed records. $/ere are t2o options for filtering t/e data in a dataset.
1. Csing t/e Select@ A met/od
2. 4ilteringa data vie2
Csing t/e Select@ A met/od and sort t/e selected data
.xample6 $o filter t/e data of students and display it
115
Im!orts "ystem.Data.BleDb
Public Class 8orm*
Dim CB44 .s 4e&
BleDbConnection(1Provider2)icrosoft.Cet.B0-DB.D.3<Data
"ource2C:;Documents and "ettings;mict?.)ICTE,)F);)y
Documents;"tudent.mdb1)
Dim olecmd .s 4e& BleDbCommand
Dim olereader .s BleDbData+eader
Dim D.da!ter .s 4e& BleDbData.da!ter
Dim D"et .s 4e& Data"et Icreate dataset obAect
Dim deci .s "tring
Dim sort .s "tring
Dim y .s Integer
Dim dt .s DataTable
Dim result() .s Data+o&
Private "ub Btnclose?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles btnclose.Clic@
)e.Close()
-nd "ub
Private "ub btndis!lay?Clic@(By:al sender .s
"ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles btndis!lay.Clic@

If chec@?valid?data() 2 8alse Then
11>
)sgBo$(1Jou must set the condition and sorting field
and o!tionK."C#D-"CL...1)
-$it "ub
-lse
If CB44."tate 2 3 Then CB44.Close()
CB44.B!en()
D.da!ter."electCommand 2 4e& BleDb.BleDbCommand
D.da!ter."electCommand.Connection 2 CB44
D.da!ter."electCommand.CommandTe$t 2 1select H from
stud1
D"et 2 4e& Data"et
D.da!ter.8ill(D"et% 1stud1)
dt 2 D"et.Tables(1"tud1)
deci 2 ComboBo$*."electedItem 7 ?
ComboBo$."electedItem 7 Te$tBo$*.Te$t
sort 2 ComboBo$3."electedItem 7 1 1 7 ComboBo$D.Te$t
result 2 dt."elect(deci% sort)
Iset datagridvie& colums headings
DataFrid:ie&*.Columns..dd(1c*1% 14umber1)
DataFrid:ie&*.Columns..dd(1c1% 14ame1)
DataFrid:ie&*.Columns..dd(1c31% 1.ge1)
DataFrid:ie&*.Columns..dd(1cD1% 1"e$1)
DataFrid:ie&*.Columns..dd(1cM1% 1Dat of Birth1)
Dim $ .s Integer 2 3
8or y 2 3 To (result.0ength E *)
DataFrid:ie&*.+o&s..dd()
DataFrid:ie&*.Item(3% $).:alue 2
result(y)(1no1).To"tring
DataFrid:ie&*.Item(*% $).:alue 2
result(y)(1name1).To"tring
DataFrid:ie&*.Item(% $).:alue 2
result(y)(1.ge1).To"tring
DataFrid:ie&*.Item(3% $).:alue 2
result(y)(1"e$1).To"tring
DataFrid:ie&*.Item(D% $).:alue 2
result(y)(1Dob1).To"tring
$ 62 *
4e$t
CB44.Close()
-nd If
-nd "ub
Private 8unction chec@?valid?data() .s Boolean
Dim ctl .s Control
8or -ach ctl In Frou!Bo$*.Controls
If Ty!eBf ctl Is ComboBo$ Br Ty!eBf ctl Is Te$tBo$
11@
Then
If ctl.Te$t NO 4othing Then
+eturn True
-lse
+eturn 8alse
-$it 8unction
-nd If
-nd If
4e$t
-nd 8unction
-nd Class
"ote 6 $/e DataTable ob=ect is used to cac/e t/e specified table from t/e dataset. nd
retrieved ro2s of record send to t/e TableRo& ob=ect and its used to get t/e record one
by one.
iltering a Data <ie&
dataVie2 ob=ect creates a fi3ed customi5ed vie2 of a given 1ata$able ob=ect.
1ataVie2 ob=ect can be considered as a mas* over a datatbale ob=ect t/at allo2s you to
filter& sort and navigate t/e contents of t/e table. $o filter data from t/e datavie2& use
Ro&ilter property and sorting data use Sort property. $/e e3ample of datafilter t/roug/
t/e datavie2 as given belo2
.xample4 Csing 1ataVie2 class to filter data.
11?
Im!orts "ystem.Data.BleDb
Public Class 8orm*
Dim CB44 .s 4e& BleDbConnection(1Provider2)icrosoft.Cet.B0-DB.
D.3<Data "ource2C:;Documents and "ettings;mict?.)ICTE,)F);)y
Documents;"tudent.mdb1)
Dim olecmd .s 4e& BleDbCommand
Dim olereader .s BleDbData+eader
Dim D.da!ter .s 4e& BleDbData.da!ter
Dim D"et .s 4e& Data"et Icreate dataset obAect
Private "ub Btnclose?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles btnclose.Clic@
)e.Close()
-nd "ub
Private "ub btndis!lay?Clic@(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles btndis!lay.Clic@
If chec@controls() 2 8alse Then
)sgBo$(1Jou must set the condition and sorting field
and o!tionK."C#D-"CL...1)
-$it "ub
-lse
If CB44."tate 2 3 Then CB44.Close()
CB44.B!en()
D.da!ter."electCommand 2 4e& BleDb.BleDbCommand
D.da!ter."electCommand.Connection 2 CB44
D.da!ter."electCommand.CommandTe$t 2 1select H from stud1
D"et 2 4e& Data"et
D.da!ter.8ill(D"et% 1stud1)
Dim dv .s 4e& Data:ie&(D"et.Tables(1stud1))
dv.+o&8ilter 2 ComboBo$*."electedItem 7 ?
ComboBo$."electedItem 7 Te$tBo$*.Te$t
dv."ort 2 ComboBo$3."electedItem 7 1 1 7 ComboBo$D.Te$t
DataFrid:ie&*.Data"ource 2 dv
CB44.Close()
-nd If
-nd "ub
Private 8unction chec@controls() .s Boolean
Dim ctl .s Control
8or -ach ctl In Frou!Bo$*.Controls
If Ty!eBf ctl Is ComboBo$ Br Ty!eBf ctl Is Te$tBo$
Then
If ctl.Te$t NO 4othing Then
11D
+eturn True
-lse
+eturn 8alse
-$it 8unction
-nd If
-nd If
4e$t
-nd 8unction
-nd Class
Connection4
$/is component is used to establis/ a connection 2it/ a data source. $2o of t/e most
common ,onnection ob=ects used are Ble1b,onnection and S9),onnection. $/e $able
given belo2 displays t/e commonly used properties and met/ods of a ,onnection ob=ect.
ConnectionString 0t provides information& suc/ as t/e data source and database
name& t/at is used to establis/ connection 2it/ a database.
%pen@ A met/od 0t is used to open a connection 2it/ t/e data source t/at is
specified in t/e ConnectionString property.
Close@ A met/od 0t is used to close t/e connection 2it/ a data source.
State property 0t is used to describe t/e current state of t/e ,onnection ob=ect.
$/e value X indicates t/at t/e connection is closed and t/e
value 5 indicates t/at t/e connection is open.
Data Command
data command is a S9) statement or a stored procedure t/at is used to retrieve& insert&delete or
modify data in a database. data command is an ob=ect of t/e Ble1bcommand or S9)command
class. data command derived from t/e Ble1bcommand class can be used to 2or* 2it/ any
Ble1+ provider& 2/ereas a data command derived from t/e S9),ommand class can be used to
access data from a S9) Server.
or .xample 6 Cse an access database& t/at /olds some student information in t/e table ^stud_
and insert a record into t/e table. ($able fields /o1/ame1Age Sex1Class and store five student
details into t/e table.)
The Data)ase Providers
(s-ccess database version 2883 - Microsoft.Jet.!E"#.$.%
(s-ccess database version 288@ - Microsoft.&'E.!E"#.().%
"nsert Ne& Record @+sing %D)C connectionA
$o insert a ne2 student details into t/e database& ,ommand !arameters
(Csing Bdbc!aarameter class)
128
using System.1ata.BdbcP
namespace %indo2s4ormspplication1
\
public partial class 4orm1 6 4orm
\
Bdbc,onnection cn Q ne2 Bdbc,onnection(M1snQS$C1#"$M)P
Bdbc,ommand odcmd Q ne2 Bdbc,ommand()P
Bdbc!arameter odpP
public 4orm1()
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
try\
cn.Bpen()P
odcmd Q ne2 Bdbc,ommand(Minsert into stud values(X&X&X&X&X)M& cn)P
odpQ ne2 Bdbc!arameter()P
odp.Value Q te3t+o31.$e3t P
odcmd.!arameters.dd(odp)P
odp Q ne2 Bdbc!arameter()P
odp.Value Q te3t+o32.$e3tP
odcmd.!arameters.dd(odp)P
odp Q ne2 Bdbc!arameter()P
odp.Value Q te3t+o33.$e3tP
odcmd.!arameters.dd(odp)P
odp Q ne2 Bdbc!arameter()P
odp.Value Q te3t+o34.$e3tP
odcmd.!arameters.dd(odp)P
odp Q ne2 Bdbc!arameter()P
odp.Value Q te3t+o35.$e3tP
121
odcmd.!arameters.dd(odp)P
odcmd.#3ecute"on9uery()P
]
catc/ (#3ception e3)
\
(essage+o3.S/o2(e3.(essage)P
]
cn.,lose()P
]
]
]
"ote 6 $ype data and clic* on t/e ne2 butoon to add ne2 details into t/e database
$/e open@ A met/od is used to open t/e connection& and E0ecute.on?uery# + met/od is
used to e3ecute t/e modifying S9) commands suc/ as 0nsert&1elete and Cpdate. $/e
Close@ A met/od is used to close t/e opened connection. #3ception /andling is optional
Delete Record @ &ith exception handlingA
$o delete specified record from t/e stud table of student database
using System.1ata.BdbcP
namespace %indo2s4ormspplication1
\
public partial class 4orm1 6 4orm
\
Bdbc,onnection cn Q ne2 Bdbc,onnection(M1snQS$C1#"$M)P
Bdbc,ommand odcmd Q ne2 Bdbc,ommand()P
Bdbc!arameter odpP
public 4orm1()
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
122
try
\
cn.Bpen()P
odcmd Q ne2 Bdbc,ommand(Mdelete from stud 2/ere YnumberZQM A
te3t+o31.$e3t & cn)P
odcmd.#3ecute"on9uery()P
]
catc/ (#3ception e3)
\
(essage+o3.S/o2(e3.(essage)P
]
cn.,lose()P
]
private void button2[,lic*(ob=ect sender& #ventrgs e)
\
t/is.,lose()P
]
]
]
"ote 6 $ype record no you 2ant to delete& t/en clic* 1elete 7ecord button.
Data Reader
0t is used to retrieve data from a data source in a read-only and for2ard only mode.
data reader uses t/e connection ob=ect to connect to t/e database& t/e ,ommand ob=ect to
e3ecute S9) statements or procedure on t/e database and retrieves t/e data in a
se;uential mode. Csing datareader results in faster access to data and less memory usage
since at any time& only a single ro2 is stored in t/e memory. ,ommonly used property
and met/od of 1ata7eader as given belo2.
Read @ A met/od 0t is used to read a ro2 of data returned by e3ecuting t/e
command on a datasource
Close@ A met/od 0t is used to close t/e 1ata7eader ob=ect
NextResult@ A
met/od
0t is used to navigate to t/e ne3t ro2 of data incase t/e
command e3ecution returns multiple ro2s of data
.xample 4 to display t/e specified student details
123
using System.1ata.BdbcP
namespace %indo2s4ormspplication1
\
public partial class 4orm1 6 4orm
\
Bdbc,onnection cn Q ne2 Bdbc,onnection(M1snQS$C1#"$M)P
Bdbc,ommand odcmd Q ne2 Bdbc,ommand()P
Bdbc1ata7eader ordrP
public 4orm1()
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
try
\
cn.Bpen()P
odcmd Q ne2 Bdbc,ommand(MSelect O from stud 2/ere YnumberZQM A
te3t+o31.$e3t& cn)P
ordr Q odcmd.#3ecute7eader()P
if (ordr.7ead())
\
if (ordr.Has7o2s)
\
te3t+o32.$e3t Q ordr.GetValue(8).$oString()P
te3t+o33.$e3t Q ordr.GetValue(1).$oString()P
te3t+o34.$e3t Q ordr.GetValue(2).$oString()P
te3t+o35.$e3t Q ordr.GetValue(3).$oString()P
te3t+o3>.$e3t Q ordr.GetValue(4).$oString()P
]
124
]
]
catc/ (#3ception e3)
\
(essage+o3.S/o2(e3.(essage)P
]
cn.,lose()P
]
]
]
"ote 6 $/e 1ata7eader ob=ect is used to collect t/e S9) commnd result for reading. $o read
record & use read@ A met/od and get t/e field data& use Wet<alue@ field indexA met/od
of datareader .
S!ntax4
*datareader ob+ect,.-et.alue/field index0.ToString
.g4 Text#ox(.Text 1 dr.-et.alue/%0.ToString
+pdating Record
$o update t/e specified student details
using System.1ata.BdbcP
namespace %indo2s4ormspplication1
\
public partial class 4orm1 6 4orm
\
Bdbc,onnection cn Q ne2 Bdbc,onnection(M1snQS$C1#"$M)P
Bdbc,ommand odcmd Q ne2 Bdbc,ommand()P
Bdbc1ata7eader ordrP
public 4orm1()
125
\
0nitiali5e,omponent()P
]
private void button1[,lic*(ob=ect sender& #ventrgs e)
\
try
\
cn.Bpen()P
odcmd Q ne2 Bdbc,ommand(MSelect O from stud 2/ere YnumberZQM A
te3t+o31.$e3t& cn)P
ordr Q odcmd.#3ecute7eader()P
if (ordr.7ead())
\
if (ordr.Has7o2s)
\
te3t+o31.$e3t Q ordr.GetValue(8).$oString()P
te3t+o32.$e3t Q ordr.GetValue(1).$oString()P
te3t+o33.$e3t Q ordr.GetValue(2).$oString()P
te3t+o34.$e3t Q ordr.GetValue(3).$oString()P
te3t+o35.$e3t Q ordr.GetValue(4).$oString()P
]
]
]
catc/ (#3ception e3)
\
(essage+o3.S/o2(e3.(essage)P
]
cn.,lose()P
]
private void button2[,lic*(ob=ect sender& #ventrgs e)
\
try
\
string st Q Mupdate stud set snameQKM A te3t+o32.$e3t A MK& ageQM A
te3t+o33.$e3t A M&se3QKM A te3t+o34.$e3t A MK&dobQKM A te3t+o35.$e3t
A MK 2/ere numberQM A te3t+o31.$e3tP
cn.Bpen()P
odcmd Q ne2 Bdbc,ommand(st& cn)P
odcmd.#3ecute"on9uery()P
cn.,lose()P
]
catc/ (#3ception e3)
\
(essage+o3.S/o2(e3.(essage)P
]
12>
]
]
]
"ote6 Get t/e record for editing ( type record no and clic* display button) and c/ange t/e
data t/en clic* update button to update data to t/e database
S?.Connection =using 5S6S?. Ser#er>
AD%-N.T is designed to provide a disconnected arc/itecture. do."#$ provides S9)
Server 1ata base connection.
S1L Server data provider 4 $/is type of data provider is used to 2or* specifically 2it/
(S-S9) server. S9) Server data provider is recommended for 2or*ing 2it/ (S-S9)
server data source& since a S9) server data provider allo2s fast access to a data source
2it/out going t/roug/ an Ble 1+ or B1+, layer. $/e S9) Server data provider classes
are present in t/e System"Data"SqlClient namesapce.
$o connect (S S9) Server and mangedata& you con use follo2ing classes
S9l,onnection
S9l1atadapter
S;l,ommand
S9)1ata7eader
S0lConnection 4 0t is used to connect t/e S;l server database.
S0lDataAdapter4 0t is similar to Ble1b1atadapter. $/e main difference is t/at t/e
Ble1b1atadapter can access any data source t/at supports B)# 1+& 2/ile t/e
S;l1atadapter supports only S9) Server 1atabases.
S0lCommnd4 S9),ommand class represents an S9) command to e3ecute against a
data store. $/e command is usually a select& insert& update& or dlete ;uery& and can be
an S;l string or a call to a stored procedure.
S0lDataReader4 to reader 1ata from t/e S;l Server database.
Parameter collection 4 !lace/olders are variables prefi3ed 2it/ an at (c) sign in t/e
S;l statementP t/ey get filled in by parameters.
.g4 to passing parameters into t/e S;l command
12@
222222222222222222222
.xample %f S1L server data management4
$o create an #mployee database into t/e S;lserver. $/e do t/e follo2ing options
>nsert data into the table
7isplay all record
7elete selected records (use datagrid:ie,
$dit selected records
1. ,reate an S;l Server database named as ^#mployee_ and create a table named as
^#mp_. $/e table fields are ("o& name& age& se3& dob& ;ualification& designation&
salary)
$/en 2rite t/e follo2ing program and run
Creating /eports
$/e reports are used to display record from t/e table as t/e printed format. ,rystal
7eports is t/e standard reporting tool for Visual Studio."et used to display data of
presentation ;uality. <ou can display multiple-level totals& c/arts& to analysis data& and
muc/ more in a ,rystal 7eport. ,reating a ,rystal 7eport re;uires minimal coding since
it is created in a designer interface.
12?
,rystal 7eports need database drivers to connect to t/e data source for accessing data.
,rystal 7eports in t/e ,-."#$ support t2o met/ods to access data from a data source.
The Pull Model
%/en t/is model is used to access data from t/e data source& t/e database driver directly
retrieves t/e data from t/e data source. $/is model does not re;uire t/e developer to 2rite
code for creating a connection and retrieving data from t/e data source. $/e crystal
7eport creates and manages t/e S9) commands for connecting to t/e data source and
retrieving data from it.
The Push Model
%/en t/is model is used to access data from t/e data source& t/e database driver directly
retrieves t/e data from t/e data source. $/e data from t/e data source is cac/ed in a
dataset and multiple ,rystal 7eports accesses t/e data from t/e dataset. $/us& t/e pus/
model allo2s filtered data access by ,rystal 7eport. $/e pus/ model as given belo2
%/e a dataset is created& it doesnot contain t/e actual data but only stores t/e description
of t/e data table& also called metadata.
To create Cr!stal Report Manuall!
%/en a ,rystal 7eport is created manually& $/e data is added manually to t/e ,rystal
7eport by using various tools from t/e ,rystal 7eport $ool+o3 and t/e 4ield #3plorer
2indo2. $o create a ,rystal 7eport manually& you can perform t/e follo2ing steps.
1. 7ig/t-clic* t/e pro=ect name in t/e solution explorer 2indo2 and point to Add
from t/e from t/e s/ort cut menu. $/en clic* Ne& "tem.
2. dd "e2 0tem 1ialog bo3 appears& select Reporting option from t/e left pane of
t/e dialog bo3
3. $/en select Cr!stal Report icon ( you 2ant c/ange t/e report name& t/en type
report name at t/e belo2 of dialog bo3) t/en clic* Add
4. "o2 add one ,rystal report 0tem into t/e pro=ect and load ,rystal7eport 1esigner.
12D
5. 4irst& accept t/e ,rystal 7eport #nd-user )icense. ,/oose ^" accept the License
AgrementR option& t/en clic* %:
>. "o2 display ,rystal 7eport Gallary 1ialog +o3. Select t/e option ^As a )lan:
ReportR t/en clic* %:-
@. "o2 display ,rystal 7eport 1esigner and ield .xplorer %indo2 at t/e left side.
$/e 7eport 1esigner displays various sections of t/e report& suc/ as 7eport /eader& page
Header& and 1etails. $/ese are6
Report /eader@ This section contains the report title( Any component that you need to
display once for the report1 you can add to the Beport Ceader Section(
Page /eader@ This section contains 8ield titles of the report( The component that you
add to the Page Ceaders section is displayed on each page of the report(
Details@ this section displays the actual :alues in the report( 8or $xample 1 if you need to
display the :alue of a field in the report1 you can add that field to the details section(
Report Footer @ The components that you add to this section is displayed at that end of
the report(
Page Footer @ The components that you add to this section is displayed at that end of the
each page of report(
?. 0n t/e 4ield #3plorer 2indo2& 7ig/t clic* t/e Data)ase ields option and c/oose
Database expert t/en display t/e database connection dialog bo3.
D. ,lic* (A) sign of t/e ,reate ne2 ,onnection option. nd e3pand t/e connection
models.
18. Select (A) sign of t/e option Database ile> display t/e 1atabase selection dialog
bo3.
11. Select your database name and clic* open button. $/en display t/e available
tables from t/e database into t/e connection dialog bo3
12. Select t/e table name you 2ant to use. nd clic* 3 button to add t/e table for
creating report. $/en clic* %:-
13. "o2 t/e selected table display in t/e ield explorer 2indo2& #3pand t/e
Database ields to s/o2 t/e table and fields.
14. $/en 1rag 4ields one by one into t/e 1etails (Section 3) section to arrage t/e
fields for display records
15. <ou can set t/e report /eading& using ,rystal 7eports tab from t/e tool bo3 and
drag te3tbo3 control to Section5 (7eport /eader) t/en type /eading ($/e same
met/od is used to set Heading for fields. 1rag control into t/e Section 6 @!age
/eader) and set t/e field /eading.)
1>. ,ontinue t/e above step to set footer /eadings (section 4 and section 5)
1@. Save t/e crystal 7eport and close 7eport 1esigner 2indo2.
138
To displa! the Report
5- Add a ne2 *indo& forms into t/e pro=ect and place t/e ,rystal7eportVie2er
control into t/e form . (4rom Reporting tab of t/e $ool +o3)
6- $/en %rite t/e forllo2ing code in side t/e 4orm[)oad event of t/e form.
Public Class 8orm
Private "ub 8orm?0oad(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles )yBase.0oad
Crystal+e!ort:ie&er*.+e!ort"ource 2
1C:;ProAects;/indo&s.!!lication*;Crystal+e!ort*.r!t1
Is!ecify the Crystal re!ort file saved !ath
-nd "ub
-nd Class
7- #3ecute t/e form2 (reportVie2er 4orm) to display t/e report.
$o filter database and display t/e details& to use Selection formula property of t/e
,rystal7portVie2er control as t/e follo2ing form
Cr!stalReport<ie&er5-Selectionormula I ^SStud-nameTI_anil_^
Br
Create an ob'ect of cr!stal report> and use ReportSelectionormula propert! as
the follo&ing form
1im ,7 as ne2 ,rystal7eport1 Ecreate ,rystal7eport1 ob=ect
,7.7eportSelection4ormulaQM\Stud.name]QKanilKM
131
,rystal7eportVie2er1.reportSourceQ,7
Br
Create a Dataset and set the dataset as datasource of the Cr!stalReport ob'ect>
see the follo&ing example
Im!orts "ystem.Data.BleDb
Public Class 8orm
Private "ub 8orm?0oad(By:al sender .s "ystem.BbAect%
By:al
e .s "ystem.-vent.rgs) Gandles )yBase.0oad
Dim dset .s 4e& Data"et
Dim cr .s 4e& Crystal+e!ort* 9create Crystal +e!ort obAect
Dim d.D. .s 4e& BleDb.BleDbData.da!ter
Dim conn .s 4e& BleDbConnection(1Provider2)icrosoft.Cet.B0-DB.
D.3<Data "ource2C:;Documents and "ettings;mict?.)ICTE,)F);)y
Documents;"tudent.mdb1)
conn.B!en()
d.D.."electCommand 2 4e& BleDb.BleDbCommand
d.D.."electCommand.Connection 2 conn
d.D.."electCommand.CommandTe$t 2 1"-0-CT H 8+B) "TPD
/G-+- K4.)-L2I.4I0I1
d.D..8ill(dset% 1stud1)
cr."etData"ource(dset)
Crystal+e!ort:ie&er*.+e!ort"ource 2 cr
conn.Close()
-nd "ub
-nd Class
SDI and 5DI Applications
0nterface is t/e ^4ace_ of t/e application as seen by t/e user iteracts 2it/ t/e application
via t/e interface.
,-."#$ provides a great deal of fle3ibility& allo2ing us to configure t/e 2or*ing
environment to best suit our individual style by providing us t/e follo2ing t2o types of
interfaces.
1. S10 (Single 1ocument 0nterface) #g6 "otepad
2. (10 ((ultiple 1ocument 0nterface) #g6 (s-%ord
132
Create SDI Appliaction
SD" 4 0n an S10 application& all t/e 2indo2s can be moved any 2/ere on t/e screen
(any a times& an interface is a =ust a single 2indo2. $/e user interacts 2it/ t/e
application t/roug/ t/is 2indo2. n e3ample of an S10 application is t/e NotePad- 0n
t/is type of interface provided application allo2ed to create or use one file at a time.
Create an 5DI Appliaction
MD"4 $/is type of interface provided applications t/at is able to /andle multiple
2indo2s at a time. lso t/e multiple 2indo2s must be /andled suc/ t/at t/ey form a
single unit. #3ample of (10 application is (icrosoft %ord.
1. 0n 4orm1 add (enustrip control and set t2o options under t/e menu Admission
1. "e2 ddmision
2. ll Student 1etails
2. 0n t/e 4orm1 properties& set "sMdiContainer properties is true- ($o ma*e a form
as (10 4orm)
3. $/en add a ne2 module into t/e pro=ect (c/oose Add Module option from t/e
pro=ect menu) and 2rite follo2ing code
4. Set t/e !ro=ect property startup ob=ect s 4orm1 (0t is an (10 from)
5. $/en #3ecute t/e pro=ect.
.I!?@ (Language-"Ntegrated 1uery)
Bne of t/e ne2 features in visual Studio 288? is )anguage-0ntegrated 9uery()0"9). t
its /eart&)0"9 is asimple Bb=ect 7elational (apping(B7() implantation. )0"9 allo2s
you& t/e programmer& to ;uic*ly design ob=ects t/at are mapped to your S9) relational
data and program against t/em in your favorite ."#$ language. <ou get t/e benefits of
full intellisense and a structure similar to one you are used to 2/en dea*ing 2it/ ob=ects.
%it/ )0"9 to S9)& you can ;uery& update&insert& and delete your data. lso you can call
stored procedures.
)0"9 can be used to ;uery more t/an databases. 0n fact& )0"9 can be used to integrate
any ob=ect t/at supports t/e 0#numerableS$T interface. $/is means an array& collection&
dictionary& and so on can be ;ueried by )in9. )in9 to S9) includes t/e designer for
133
mapping tables& vie2s and ot/er database ob=ects to ."#$ classes called entity classes.
%/en you instantiate an #ntity class in your code it is called an entity.
#3ample of )0"9 accessing as given belo2
Note4 $o e3ecute )0"9& 7e;uired ."#$ frame2or* 3.5.
.xample as given belo& 4 to read data from t/e s9) database
1. create a ne2 2indo2s forms appliaction called ^)in;$oS9)_
2. "e3t& add a ne2 )0"9 to S9) classes item to t/e pro=ect (!ro=ect menu-T dd "e2
items-T c/oose QLin1 to S1L classesR> clic* BJ
3. "o2 display designer 2indo2.
4. Select Server e3plorer and ma*e a connection for s;l darabase. (c/oose above created
emplo!ee database)
5. nd selected table @empA and 1rag into t/e L"N1 Designer *indo& &no2 display
your table into t/e 2indo2
>. $/en clic* dataclasses1 designer 2indo2& no2 display t/e property. $/en c/ange t/e
name property to ^empdatacontextR
@. Save t/e pro=ect and select t/e 2indo2s form ( form1). nd place one datagridvie&
control into t/e form
?. $/en 2rite t/e follo2ing code into t/e form load event
Public Class 8orm*
Private "ub 8orm*?0oad(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles )yBase.0oad

"im empdb &s 2ew emp"ata'ontext
"im S &s String
"im tb 1 3rom emp 4n empdb.EMPs 5here emp.&-E , )% select emp
6lin7 8uery
"ata-rid.iew(."ataSource 1 tb
-nd "ub
Private "ub Button*?Clic@?*(By:al sender .s "ystem.BbAect%
By:al e .s "ystem.-vent.rgs) Gandles Button*.Clic@
)e.Close()
-nd "ub
-nd Class
D. #3ecute t/e program and see t/e result.
Stucture of L"N1 1uer!
134
)0"9 ;uery& often referred to as a Duery expression& consists of a combination of
;uery clauses t/at identify t/e data sources and iteration variables for t/e ;uery. ;uery
e3pression can also include instructions for sorting& filtering& grouping& and =oining& or
calculations to apply to t/e source data. 9uery e3pression synta3 resembles t/e synta3 of
S9)P t/erefore& you may find muc/ of t/e synta3 familiar
Dim Query+esults 2 8rom NvariableO In Ndatabase nameO
"elect NvaraibleO
#g6 1im rs Q from cust in customers select cust
.g 6 6 +sing S0l condition (%/ere ,lause)
Dim Query+esults 2 8rom cust In customers ?
/here cust.Country 2 1P".1 ?
"elect cust.Com!any4ame% cust.Country
.g4 7 $/e follo2ing code e3ample s/o2s a ;uery e3pression t/at combines customer and order
data and returns a collection of anonymous types containing customer and order data.
Dim Query+esults 2 8rom cust In customers% ord In orders /here
cust.CustomerID 2 ord.CustomerID "elect cust% ord
+sing Wroup `oin
.g4 8 <ou can use t/e Wroup `oin clause to create a /ierarc/ical ;uery result t/at contains a
collection of customer ob=ects.
Dim Query+esults 2 8rom cust In customers ?
Frou! Coin ord In orders Bn ?
cust.CustomerID -Quals ord.CustomerID ?
Into CustomerBrders 2 Frou!% ?
BrderTotal 2 "um(ord.Total) ?
"elect cust.Com!any4ame% cust.CustomerID% ?
CustomerBrders% BrderTotal
Visual *asic .I!? ?uery 2perators
$/e classes in t/e System.)in; namespace and t/e ot/er namespaces t/at support )0"9 ;ueries
include met/ods t/at you can call to create and refine ;ueries based on t/e needs of your
application. Visual +asic includes *ey2ords for t/e most common ;uery clauses& as described by
t/e follo2ing table.
rom Clause @<isual )asicA
#it/er a rom clause or an Aggregate clause is re;uired to begin a ;uery. rom clause
specifies a source collection and an iteration variable for a ;uery. 4or e3ample6
Synta36
135
8rom element K .s type L In collection K ? L
K% element2 K .s type2 L In collection2 K% ... L L
.g4 Dim names 2 3rom cust In customers /here cust."tate 2 1/.1
"elect cust.Com!any4ame
Select Clause @<isual )asicA
Bptional. 1eclares a set of iteration variables for a ;uery. 0f a Select clause is not specified& t/e
iteration variables for t/e ;uery consist of t/e iteration variables specified by t/e rom or
Aggregate clause. 4or e3ample6
"ynta$:
"elect K var1 2 L fieldName1 K% K var2 2 L fieldName2 K...L L
Eg:
Dim customer0ist 2 8rom cust In customers
"elect cust.Com!any4ame% cust.ID
*here Clause @<isual )asicA
Bptional. Specifies a filtering condition for a ;uery. 4or e3ample6
Syntax: 5here 'ondition
Eg: Dim names 2 8rom !roduct In !roducts ?
/here !roduct.Category 2 1Beverages1 ?
"elect !roduct.4ame
%rder )! Clause @<isual )asicA
Bptional. Specifies t/e sort order for columns in a ;uery. 4or e3ample6
.g4 K 7eturns a list of boo*s sorted by price in ascending order.
1im titlesscending!rice Q 4rom b 0n +oo*s Brder +y b.!rice
`oin Clause @<isual )asicA
Bptional. ,ombines t2o collections into a single collection. 4or e3ample6
"ynta$:
.oin element 0n collection Y 2oinClause [ Z Y groupEoinClause ... [ Z Bn +ey% #;uals +ey&
Y nd +ey6 #;uals +eyF Y... Z
.W4 1im processes Q 4rom proc 0n !rocess.Get!rocesses .oin desc 0n process1escriptions [
Bn proc.!rocess"ame #;uals desc.!rocess"ame Select proc.!rocess"ame&
proc.0d& desc.1escription
.xamples
13>
5- The follo&ing code example performs an implicit 'oin to combine a list of
customers &ith their orders.
Dim customer01s() Q \M)4J0M& MV0,$#M& M+)CSM& M$70HM]
Dim customer)ist Q rom cust "n customers& cust01 "n customer01s [
%/ere cust.,ustomer01 Q cust01 [
Select cust.,ompany"ame
or .ach company"ame "n customer)ist
,onsole.%rite)ine(company"ame)
Next
Aggregate Clause @<isual )asicA
$/e Aggregate clause can be used to include aggregate functions in your ;ueries.
ggregate functions perform c/ec*s and computations over a set of values and return a
single value. <ou can access t/e computed value by using a member of t/e ;uery result
type. $/e standard aggregate functions t/at you can use are t/e All& An!& Average&
Count& LongCount& Max& Min& and Sum functions.
Synta36
ggregate element Ys typeZ 0n collection Y& element& Ys type&Z 0n collection&& Y...ZZ
Y clause Z 0nto expressionList
.xamples4
ALL
Dim customer)ist1 Q ggregate order "n orders 0nto llBrdersBver188 Q ll(order.$otal TQ
188)
AN$
Dim customer)ist2 Q rom cust "n customers ggregate order "n cust.Brders [
0nto nyBrderBver588 Q ny(order.$otal TQ 588)
A<.RAW.
Dim customerBrderverage Q ggregate order "n orders 0nto verage(order.$otal)
C%+NT
,ounts t/e number of elements in t/e collection. <ou can supply an optional )oolean e3pression
to count only t/e number of elements in t/e collection t/at satisfy a condition. 4ollo2ing is an
e3ample6
.g4 Dim customerBrderfter1DD> Q rom cust "n customers ggregate order "n cust.Brders
0nto ,ount(order.Brder1ate T -12N31N1DD>-)
13@
MA9
,omputes t/e ma3imum value from t/e collection& or computes a supplied e3pression for all
elements in t/e collection. 4ollo2ing is an e3ample6
Dim customer(a3Brder Q ggregate order "n orders 0nto (a3Brder Q (a3(order.$otal)
M"N
,omputes t/e minimum value from t/e collection& or computes a supplied e3pression for all
elements in t/e collection. 4ollo2ing is an e3ample6
Dim customer(inBrder Q rom cust "n customers ggregate order "n cust.Brders [
0nto (inBrder Q (in(order.$otal)
S+M
,omputes t/e sum of all elements in t/e collection& or computes a supplied e3pression for all
elements in t/e collection. 4ollo2ing is an e3ample
Dim customer$otals Q rom cust "n customers ggregate order "n cust.Brders [
0nto Sum(order.$otal)
.xample4 To connect database using S0lDataAdapter &ith L"N1
Im!orts "ystem.0inQ
Im!orts "ystem.Data."QlClient
)odule )odule*
Public filldataset .s 4e& "QlData.da!ter
Public con .s 4e& "QlConnection(1Data "ource2(local)<Initial
Catalog2-)P0BJ--<Integrated "ecurity2True1)
"ub )ain()
getdata()
Console.+ead,ey()
-nd "ub
Public "ub getdata()
Try
Dim connection"tring .s "tring
Dim ds .s 4e& Data"et
Dim da .s 4e& "QlData.da!ter

da."electCommand 2 4e& "QlCommand
da."electCommand.Connection 2 con
da."electCommand.CommandTe$t 2 1"elect H from em!1
da.8ill(ds% 1em!1)
Dim orders .s DataTable 2 ds.Tables(1em!1)
Dim Query 2 8rom em! In ds.Tables(1em!1) "elect em!
9linQ Query
8or -ach ! In Query
Console./rite0ine(!.8ield(Bf Decimal)(1no1) 7 ?
13?
vbTab 7 !.8ield(Bf "tring)(14ame1) 7 vbTab 7 ?
!.8ield(Bf Decimal)(1age1) 7 vbTab 7 ?
!.8ield(Bf "tring)(1"e$1) 7 vbTab 7 ?
!.8ield(Bf DateTime)(1DBB1) 7 vbTab 7 ?
Trim(!.8ield(Bf "tring)(1Rualification1)) 7 ?
vbTab 7 Trim(!.8ield(Bf "tring)(1Designation1)) ?
7 vbTab 7 !.8ield(Bf decimal)(1salary1)
.To"tring(1S.SS1))
4e$t
Catch e$ .s "Ql-$ce!tion
Console./rite0ine(1"R0 e$ce!tion occurred: 1 7
e$.)essage)
-nd Try
-nd "ub
-nd )odule
Deploying 7our Application
1eployment is t/e activity of delivering copies of an application to ot/er mac/ines so t/at
t/e application runs in t/e ne2 environment. 0t is t/e larger& arc/itectural vie2 for 2/at
you may *no2 as installation or setup.$/ere is a subtle difference bet2een deployment
and installation.
1eployment is t/e art of t/e distribution. 0n ot/er 2ords& deployment is t/e 2ay in 2/ic/
soft2are is delivered.
$/e installation or setup is a process& 2/ere you load& configure& and install t/e soft2are.
So an installation is 2/at you do to configure t/e soft2are& and deployment is /o2 you
get it 2/ere you 2ant it.
or example to create a deplo!ment pro'ect of !our application do the follo&ing steps
1. Bpen your pro=ects
2. dd a setup pro=ect to t/e solution& named "nstaller. ( 4ile menu-T c/oose dd -T
ne2 pro=ect from t/e main menu bar)
3. dd ne2 pro=ect 1ialog bo3 appears& select #3pand %ther pro'ect t!pes Bption
from t/e pro=ect type pane. nd c/oose sub option Setup and Deplo!ment.
4. $/en select Setup Pro'ect icon from t/e template panel & and type name "nstaller
t/en clic* BJ
5. %/en Visual Studio creates t/e pro=ect& it adds a 1esigner. $/ere are t/ree main
folders in t/e left pane of t/e 1esigner.
pplication 4older
CserFs 1es*top
13D
CserFs !rogram (enu.
>. 0n t/e Solution e3plorer& rig/t clic* t/e "nstaller pro=ect and c/oose Properties
@. "o2 "nstaller Propert! Page dialog bo3 appears. $/en clic* prere0uisite button
?. 1isplay !rere;uisites dialog bo3 and select t/e c/ec* bo3 besides t/e follo2ing
items
5icroso!t Data *ccess Components A"B
)indows installer C"D
".ET !ramewor, C"E
$o include reports in your application& select t/e follo2ing items
Crystal Report 2asics !or 6isual studio AFFB #0BG,0GH+
5icroso!t 'isual StudioAFFB report 'iewer
D. Select t/e Bption ? 7o,nload prereDuisites from the same location as my application@
and clic* B* and clic* BJ (close 0nstaller !roperty !age dialog bo3)
18. 7ig/t-clic* t/e Application older node in t/e 1esigner (left !ane) and select dd-T
!ro=ect Butput.
11. $o display Pro'ect %utput dialog bo3& c/oose Primar! output option and clic* BJ
12. $/en rig/t-clic* on t/e item QPrimar! output from @!our application nameA @ActiveAR
and c/oose t/e option QCreate shortcut to primar! output from @ !our applicationAR
13. "o2 create one shortcut into t/e rig/t pane of t/e designer.
14. 7ig/t-clic* t/e ne2ly created s/ortcut and select cut from t/e conte3t menu. Bn t/e left
pane& rig/t-clic* +ser]s Program Menu and clic* Paste (<ou 2ant to c/ange t/e s/ort
cut name& rig/t-clic* t/e s/ortcut and c/oose rename and type your name)
148
5J- Save and )uild the "nstaller Pro'ect-
To install $our application
Bpen M! Computer and select D.)+W folder from t/e "nstaller folder from !our
pro'ect. nd 1ouble ,lic* on t/e "nstaller "con ( %indo2s installer pac*age)Z
3ser Interface "ditor
%it/ t/e user 0nterface #ditor& you can configure t/e installation to do =ust about
anyt/ing you 2ant. <ou can add prebuilt dialog bo3es suc/ as )icense agreement. lso a
number of customi5able dialog bo3es are available <ou can even add a custom dialog
bo3 to ensure t/at a valid serial number is entered during installation.
1. Bpen previously created deployment pro=ect
2. $/en select Vie2 menu -T #ditor -T Cser 0nterface
3. $/e editor 2ill be open (above displayed)
4. <ou 2ill see t2o main items. 0nstall and dministrative 0nstall bot/ /ave customi5able
interfaces
5. Cnder t/e "nstall node at t/e top& rig/t clic* Start and c/oose Add Dialog from t/e
conte3t menu.
>. "o2 display dialog bo3& select License Agreement dialog bo3 and clic* B*. $o add t/ese
dialog bo3 at t/e last position of 0nstall node.
@. 7ig/t-clic* t/e )icense agreement dialog bo3 and c/oose Move +p to set t/e position as
second (under of 2elcome)
141
?. Select )icense agreement dialog and c/ange t/e )itmap & and License file !roperty
( license file must /ave type .7$4 file& +itmap is banner image of dialog bo3 )
D. "e3t& dd a Custom "nformation 1ialog bo3 and ma*e it t/e $/ird step under t/e Start
process. ,/ange t/e SerialNumberTemplate property to HH/,,,/HHH and t/e
Sho&SerialNumer to Ture
18. Then `ust build the application and "nstall
2//////////////////////////////////3
142

You might also like