You are on page 1of 24

12

Data Access
with AD0.NET
If you need an Information on:
See page

Understanding Databases 498

Understanding SQL 498

Understanding ADO.NET 501

Typed Vs. Untyped DataSets 506

DataReader 506

Creating Connection Strings 508

Creating a Connection to a Database 511

Creating a Command Object 530

Working with DataAdapters 531

Using DataReader to Work with Databases 539


Chapter 12 Data Access with ADO.NET
communicate with file-basod
ADO.NET, of Microsoft .NET Framework, allows your application to easily Iet's learn the
basics of SQL in the next section.
a
part
and server-based data sources. ADO.NET Iibraries appear under the System. Data namespace in the .NET
of ADO.NET is to communicate with the data and provide data accese The SELECT Statement
Framework. The most important use
services to the NET Framework. It provides access to various kinds of data, such as Extensible Markn You can use the SELECT statement to retrieve records from a table. The following is an example to retrieve all
Language (XML), relational, and applicaion data. In addition to data accesS, it supports creation of front-end the records in the Customers table, by using the wildcard character
database clients and middle-tier business objects.
SELECT FROM Customers
ADO.NET provides consistent access to data sources, such as SQL Server, XML, and data sources exposed The preceding example returns a Dataset that holds allthe records in the Custome rs table. You can also use the
through Object Linking and Embedding Database (OLE DB), and Open Database Connectivity (ODBC). It also SELECT statement to select specific fields from a table, as shown in the following example:
separates data access from data manipulation and includes separate data providers for connecting to a database, SELECT CustomerID, Address, City FROM Customers
executing commands, and retrieving results. DataSet that holds all the records in the Customers table, and each record has
The precedingexample returns
a
In this chapter, vou learn how to access data by using ADO.NET. You also get acquainted with database and its and city field.
a Custome rID, Address,
various
components. In addition, you lean about the basic SQL statements, the ADO.NET architecture, and its
vanous components. Finally, you learn about the ADO.NET Entity Framework. The WHERE Clause
In SQL, you can use the WHERE clause to specify a you want all the records to meet. For example, to
criterion that
Understanding Databases select all the records in the Customer s table, where the City field holds London, you can execute the following
Database in simple collection of structured information. It stores information in an
terms means a
structured manner to facilitate the retrieval as and when organized and statement:
SELECT * FROM Customers WHERE City = 'London"
the years; however, the fundamental
required. Databases have become more complex over
concept is still a simple one. For example, suppose you are a teacher, who The other operators that can be used in the WHERE clauses are as follows:
requires allotting the grades for each student. You
might make a table on a paper and enter the grades of the
students in that table and name it, the
studentstable table. In this example, you have a (less than)
database-or more already created a
specitically, database table on paper. Now, you can make the similar table on the
a o -(less than or equal to)
that allows you to sort, index,
update, and organize any size of tables in an easy way. computer
A collection of records, that is,
rows of records, where each
>(greater than)
common form, a database is
column is a field, becomes a table. In its most O>(greater than or equal to)
merely a collection of one or more tables. However, there is another
database as well-relational
database. It is called so because the relational databases are set up such that the type of oBETWEEN
in
multiple tables can be related to one another. To make a table data
IN
keys and foreign keys. relational, you select certain fields to be primary
LIKE
The
primary key in a table is usually the most
duplicate values important
one- you can differentiate between records containing
on the basis of
key, primary as the
primary key column does not contains duplicate value. The The LIKE Clause
foreign key usually represents the specify with wildcards. You can select
primary key
organized way. for example, you might add a field
in another table, which
gives you access to that table in an n SQL, the LIKE clause allows you to use the partial string that you can
This is shown
Lo %.
called studentsid to the records from the Customers table, where the City field matches the wildcard string
field, studentsid,
may be the studentstable table. The samne a the
table, the student id field is primary
s
key in the school registrar's database table that lists all
then a foreign key, students. In our
in the following SQL query statement:
table. allowing us to specify individual records in the SELECT FROM Customers wHERE City LIKE LO%
registrar s DataSet which contains only those records whose City
field contains names
You work with the data
can
he
preceding example creates a
combinations for using the s wildcard
present in a database by using Structured with Lo, such Los Angeles or London. The three possible
elaborately defined later in this chapter. Query Language (SQL), which has been Sarung as

typically returns a Data Set of records that matches sQL to set up a query, which, when applied to a database,
use
character are as follows:
information about all the students who your SQL query. For example, D Lo%-Returns all the items starting with Lo, such as London or L0s Angeles.
got B grade or better. You can do you may set up a query to
records, creating new tables, and several things, such as Be o %Lo- Returns all the items ending with Lo, such as Säo Paulo.
getting datasets by using SQL. insering new
Therefore, you can use SQL field value, such as Barcelona.
filter out the records
all the items containing Lo anywhere in the
to
you do not want and then work oLo%-Returns
a built-in tool (the Query Builder) that allows you to create on them. The SQL Server has
SQL statements The DISTINCT Clause
visually.
Understanding
SQL
SQL
is
in the fields of a table. For example,
Omemes a database may hold duplicate valuesthe same value in the City field. You might want to take a look
several customers come

a standard interactive and would have


databases.It is programming
designed to retneve and manage language for
querying and n e same cities, therefore they You can use the DISTINCT clause
to avoid repetition, as
shown

(RDEMS),creale and modity a database schema, data in Relati


onal
modifying data and mana ging h e Cities represented, without repetition.
and Database Management in the following SQL query statement
We learn to work with manage a database object Sys tem
and other fields, and a
a database that contains a table named Cust
control. SELECT DISTINCT City FROM Customers
table named orde rs omers
holding the customer
the Northwind database. holding the fields for the
customer orders. These
IDs, addresses, The Logical Operations the
tables are based on records from the database on
need to retrieve the
used in a situation when you those records
whose
operators are
498 Ecal
conditions. Let's take an example in
which you want to retrieve only
OSome logical
499
Chapter 2 have some value (we use the Te
Data Access with ADo.NET
York, and the
Fax field should NOTN
city should neither be
Boston or
statement can retrieve tho
be used to retrieve the The DROP Statement
kevword to check if the Fax
field contains any value).
Following
required DROP Statement in SQL removes an
A
object from the database. You can use the DROP
statement to remove
records. AND Fax IS NOT NULL 11ser, or even an entire database. You a
City
WHERE NOT IN (BOoston,York") table,i can remove the Customers table from the
database, as shown
SELECT FROM Customers OR, and NOT. Using AND means that both. following SQL query statement
in the
to connect the clauses AND, uses
use these logical operators
You can
NOT tlips the value of a clause from
m DROP TABLE CUstomer
either one can be True, and using True to
must be True, using OR means
False or rom False to
True.
Understanding ADO.NET
The ORDER BY Clause ADO.NET is the data access and manipulation protocol used by the .NET Framework. It uses a disconnected
You can order the records in the DataSet by using
an SQL statement. You can order the records of the data architecture, which means that the data you work with is just a copy of the data in the actual database.
Customers table by CustomerID, a s shown in the following example: Microsoft chose disconnec ted da ta architecture for a number of reasons. In traditional client/server applications,
vou get a connection to a database and keep it open, while the application is running. However, maintaining
BY CustomerID
SELECTFROM Customers ORDER these connections takes up a lot of server resources. In addition, if you want to migrate to the Internet you have
You can also sort the records in descending order using the Desc keyword:
SELECT FROM Customers ORDER BY Cus tomerID Desc to maintain disconnec ted DataSets, instead of maintaining direct and continuous connections.
ADO.NET provides a setofcomponents to createdistributed applications. It is an important and integral part of
NOTE
If you are not providing the Desc keyword with the ORDER BY clause, it wil, by defaulit, retum results in ascending
a NET Framework. ADO.NET provides a consistent access to data sources, such as Microsoft SQL Server,
OLEDB, Oracle and XML. In addition, you can use ADO.NET to retrieve, manipulate, and update data present
order. in these data sources. ADO.NET includes data providers for connecting to a database, executing commands, and
retrieving results. These results are either directly or placed in the ADO.NET DataSet object to be
processed
The GROUP BY Clause exposed to the user in a temporary manner. The ADO.NET classes are found in and are
System. Data.dll
The integrated with the XML classes found in System. Kml dll. Some of the important features of ADO.NET are as
GROUP BY clause of SQL is used to group some records according to the fields of the table.
.

You can group


records in SQL with the GROUP BY clause as shown in the following SQL query statement: follows:

SELECT OrderID, SUM(Quanti ty) FROM orderdetai1s GROUP BY OrderID o LINQ-Stands for Language-Integrated Query integrated into various aspects of data accessin a NET
In the preceding example, we are grouping them by Order ID. Framework which includes Dataset disconnected programming model and the existing SQL Server
database schemas. LINQ to ADO.NET consists of three separate technologies: LINQ to DataSet, LINQ
to

The DELETE Statement SQL, and LINQ to Entities. LINQ to DataSet provides better querying over DataSet. LINQ to SQL
The DELETE statement in SQL is used to delete the records from a
table. You can use the WHERE clause with the enables you to directly query SQL Server databases. The LINQ to technology is used to expose the
Entities
DELETE statement to delete the records on the basis of some relational data objects in the .NET environment.
conditions as shown in the SQL following query
statement to DataSet-Provides LINQ capabilities for disconnected data stored in DataSet. LINQ to

DELETE FROM Customers WHERE Ci ty NOT IN


O LINQ
C'BOston York) easier and faster to query data cached in a DataSet object. The LINQ to DataSet
In the
preceding example, 2NLG DataSet makes it over

contain the value Boston or York.


we are
deleting the records from the Customers table whose
City field does not feature enables you to work more productively.
You can use the
SQL-Provides a run-time infrastructure for managing relational data objects.
as
O LINQ to
The UPDATE Statement SQL feature of ADO.NET to use the LINQ technology
LINQ to
to access SQL databases in the same manner
would
You the UPDATE statement to collection. LINQ to SQL supports all the key capabilities that you
can use
update
a database. You can
as
you would access an in-memory
use the WHERE clause with the
UPDAI and delete the information from the table.
statement to update the records on the basis of
condition. This is shown in the expect while working with SQL. You can insert, update,
or C#
UPDATE Customers SET
City 'Boston' WHERE City
=
following SQL query statement OLINQ to Entities Allows developers to create queries against
-
the database using the Visual Basic
In the York' =
command tree queries and
preceding example, we are changing the City to Boston in all Entities is used to convert LINQ queries to
records where it is York at programming language. The LNQ to used by the
present return result in objects that can be
them against the Entity Framework. These queries
Joining Tables executes
.NET Framework.
You can join
two or more tables in a
database with SQL. For
Now, example, you work with relational es.

the items
you want to create a new DataSet with
they have ordered from the
customer contact names from
can

the Customers table and


dataoa
Ds o NOTE
YOU Will lean more about LINQ in detail in Chapter 13, Working wih LINO.
tne
Orders table. The field that
therefore you relates these two tables is
SELECT
can set
up the SQL query as shown in the
following code snippet Custome rID
The following is a list of most common ADO.NET objects:
CUstomers.ContactName,
Customers, ordersWHERE
orders.orderID FROM
the data to read and write data with the help
o

orders.CustomerID Customers.customerID = he Connection object-Provides a connection to source

or Sql C o n n e c t i o n objects.
OracleConnection
The
preceding code snippet ensures that the OLeDbConnection, OdbcConnecti on,
Cust omerID field matches in each record communication between a data source and a DataSet. You ypically
You can also do DataAdapter object-Provides are the
table.
inner joins, where records must be in both
you are joining The
with SQL to execute against
the data source. The
available DataAdapters
tables, or outer joins, where records can be either Contigure a DataAdapter o r a c l e Data Adapter,
and SqlDataAdap
t e r objects.

OeDbDataAdapter, Odbc DataAdapter,

500 501
Data Access with AD0.NET
delete the records ina
and
Chapter 12 to read,
ada, update, aSupport asynchronous programming-Provides support for implementing asynchronous
for

The
Command object-Allows
four properies
DataAdapters
that give you
access to these

creating
objects- Sel
SelectComma
queria
ies o nmand
programming in a simpler manner. ADO.NET provides various methods, such as BeginExecute NonQuery)
O tor
and BeginExecuteReader(), to support asynchronous programming. It also provides a modifier, named
Data Adapters
support and
D e l e t e c o m m a n d

data
U p d a t e C o m m a n d ,
async, which indicates that a method is asynchronous.
The shrasal
I n s e r t C o m m a n d ,

source.
disconnected
from the data ucture of OSupport for high availability- Enables you to work with the AlwaysOn Availability Groups feature that
source that is
DataSet is similar to that of a data
relational database;
in a cache it allows you to access the data in the form
are supported
of + wilh
The DataSet object-Stores
sunn
tables, o was introduced in SQL Server 2012. An AlwaysOn Availability Group refers to a container comprising a set
D for the tables. DataSets are
of databases that can failover together. ADO NET introduces two new connection properties that can be
defined
constraints and relationships
and columns;
and contains
used in the SqlClient data provider for connecting a .NET application lo a server in an availability group or
and
DataSet objects. data source. Data tables contain two
importa SQL Server 2012 Failover Cluster Instance. These properties are
Application Intent
data table from
a
the columnan MultiSubnet Failover.
OThe DataTable
object-Holds a collection of the DataColumn objects that represent ns
dat
which is a the rowS of data in a table Support for LocalDB databases-Enables you to work with Express LocalDB, which is a lightweight
properties-Col umns, representing
collection of
which is a Dat aRow objects, version of SQL Server introduced in SQL Server 2012. The Express LocalDB
edition has all the core
ina table, and Rows, read-only, forward-only (you
can only m o v e from one record the program
The DataReader object- Holds a
database. Using a data reader can increaee
ease speed functionalities of the SQL Server Express edition and it is specifically developed for
o
not backwards)
set of data from
a
developers. It is easy to install without having
a lot of
pre-requisites to be installed. The installation of the
succeeding record, at a time. edition copies only those files that are required to start SQL Server Database Engine.
You
because only one row
of data is in memory Express LocalDB
view of a single table
that can be filtered, searched
ed,
or DB.exe utility to create and maintain an instance of the SQL Server 2012 Express
a customized can use the SqlLocal
The DataView object-Represents the DataView class, is
a data snapshot that takes unf in ADO.NET provides full support for working with this new
O
data view, supported by LocalDB edition. The SqlClient data provider
sorted. In other words, a edition of SQL Server.
resources of Datasets. A
supported by constraint, to send password in as Securestring object over the network to
the data integrity with the support SecureString class- Enables developers
The Constraint object- Checks
O
O or deleted to check the
are inserted, updated, ensure the secure data transter.
rule that can be used when rows
the Constraint class, is a which check that
There are three types of constraints: traints, cons that are supported by the ADO NET
affected table after the operation.
unique
O Support for data tracing-Provides built-in data tracing features
the table; foreign-key constraints, which specify how OLE DB,
and the .NET data providers for SQL Server, Oracle,
the new values in a column are unique throughout DataSet, the SQL Server network protocols,
record in another table is updated; and primary key constrains the following data access problems:
related records should be updated when a and ODBC. This helps in troubleshooting
constraints. The difference between the unique and primary key
which work similar to the unique Unavailability of a database
allows null values; whereas, the primary key constraints does
constraints is that the unique cons traints its associated database
be applied on more than one column in table Schema mismatch between an application and
allow null values. In addition, the unique constrains can
whereas, the primary key constraints can be applied on one column only. Incorrect programming logic
OThe DataRelation object-Specifies a relationship between parent and child tables based on a key that both Incorrect SQL queries
tables share. with external components
Issues resulting in using ADO.NET
the Item
o The DataRow object-Corresponds to a particular row in a data table. You can use
property Issues resulting in using multiple ADO.NET components class
get or set a value in a particular field in the row. class-Resides in the System.Data.SQLClient namespace. The SqlCredentialclass
OThe SqlCredential in the SqlCredential is
o The Data Column object-Corresponds to the columns in a table. Each object has a Dat aType propery The password
includes a user id anda password for SQL Server authentication.
that specifies the kind of data each column contains, such as integers or string values. an object of the Securestring type.
named Encrypt, which is used to encrVpt
Now, let's learm about the new features introduced in ADO.NET in .NET Framework 4.5. connection option-Provides a keyword,
OSupport for the Encrypt and a SQL Server database. When
the Encrypt keyword is

transfers betweena client application


New Features of ADO.NET in .NET Framework 4.5 all the data
connection string, the SQL Server database uses the Secure Socket Layer encryption
set to true in a
As already discussed, ADO.NET is one of the important components of the.NET Framework that is used to encrypt the data.
technique GetTableSchema()
to access diferent data sources and data services in NET applications. Some new features and in data access operations. The
S u p p o r t for sparse columns-Provides high performance When a column is using the
enhancements are introduced in ADO.NET Framework in .NET Framework 4.5. The new features method of the SqlDataReader class provides metadata for all the columns.
returns IsColumnSet
as
ADO.NET are discussed as GetSchemaTable ) method
follows sparse feature and it is
a member of the column set, the
OStreaming support in SqlClient-Allows you to store and access unstructured data, such as true.
images, and video files, to and from SQL Server through .NET aoc e assembly-
data types. In ADONET
Includes spatial
unstructured data from SQL Server, some new applications. To enable you to acces ONew version of the Microsoft.SqlServer.Types.dll
has been upgraded from
version 10.0 to version
Ir you
ll.0.
methods are introduced in the assembly
DbDataReaa
sqlDatareader classes that are used to obtain data from SQL queries in NET applications. The meethods 4.5, the Microsoft.SqlServer.Types.dl with version 10.0, then the application
may tail to

that references the assembly


application
added to the Sql DataReader are using an
class include
GetFieldValueAsyne (), tsDBNullAsync (), GetFieldValueother build. Server 2012 value for
the Type
hand, the methods added Get.Stream (0, GetText Reader (), and GetXml Version property-Provides
the new SQL
to the
DbDataReader class Reader (). and New value for the Type System Version = Latest is obsolete and equivalent to Type
GetTextReader ().
are
GetFieldValue (), GetStream System Version property. The old
value Type System
System Version SQL Server 2008.
= Framework 5.0.

developers to use new


features of the Entity
Framework 5.0-Allows
S u p p o r t for Entity 503
502
Chepter 12 Data Access wlth
ahead to discuss the
ADO.NET architecture. mand- Executes a
command against ADO.NET
Let's now move the data
source and retrieve
INSERT, UPDATE, or DELETE
the a
DataReader or
Architecture of ADO.NET mand objects is the DbCommand class.command against the data source. The baseDataSet. It also
class for all
the Dat aSet, which is disconnected from the lata The Command
ADO.NET consists of two fundamental
components:
and the .NET data provider, which allSoue
CICommand, OleDbCommand, Oraclecommand and object is
represented by four classes:
and does not need to know from
where the data is retrieved;
commands against it. The DataSet is designed for
to do methods that are used to execute commands onOdbcCommand.
the database. The
The Command
object provides
connect tothe data source and execute the SQL
data from tradititional e
vecutes the commands, such INSERT, UPDATE, as
ExecuteNonQuery0 method
vocuteScalar() method returns single value from database DELETE
or
can be used in the same way to manipulate a that have
independent of any data source.It a return value. The no
a
tor
data manipula tion and read onlud query. The Execute Reader( method returns
source or from an XML document.
The data providers are
designed only access a result set by way of the Data Reader object.
of data. The architecture of ADO.NET is explained illustratively in Figure 12.1:
DataReader- Provides torward-only and read-only connected result set. The base class all
a

DataReader objects is the for


NET Framework Data Provider DataSet
DbDat aRea der class. The DataReader object is represented by four DataReader
DataAdapter
DatsTableCollection elasses: SqIData Reader, OracleDa ta Reader, OleDbData Reader, and
the
OdbcDataReader. The DataReader
Connection
object cannot be instantiated.
directly
DataTable
Sect Comesed Data Adapter-Updates the DataSet with data from the data
source. The base class for all
obiects is the DbDataAdapter class. The DataAdapter acts as an Dat aAdapter
DstaRowCollection intermediary for all the communication
between the database and DataSet. The DataAdapter is used to fill a DataTable or DataSet with data
Command from the database using the Fill () method. The DataAdapter commits the
Dtcomncelertian
changes to the database by
calling the Update () method. The Data'Adapter provides four properties that represent the database
Update Co d command: SelectCommand, InsertCommand, DeleteCommand, and UpdateCommand.
Comstraintcolection
Data Provider in ADO.NET
Data Reader Deleta Comand
The different types of data providers included in ADO.NET are as follows:

DataRelationt ction
o.NET Framework Data Provider for SQL Server-Provides access to Microsoft SQL Server. It uses the
System. Data. SqlClient namespace and its own protocol to communicate with the SQL Server. It
performs well when used to access a SQL Server. There is no need to add an OLE DB or the ODBC (Open
Database Connectivity) layer to access the data provider. You can use the . NET Framework Data
Provider for soL Server, when you have access to SQL Server 7.0 or later versions.

aNET Framework Data Providerfor OLE DB-Provides acess


to data sources exposed by using OLE DB.
for both local and distributed transactions.
Figure 12.1: Showing the ADO.NET Architecture It uses the
Sys tem . Data.0leDb namespace and holds support
As you in access to data sources exposed by using ODBC. It
can see
Figure 12.1, the data provider
contains the Connection, Command, O .NET Framework Data Provider for ODBC- Provides
DataAdapter objects. The Connection
object provides connectivity
DataRe ader, and
to the data source. The Command uses the System. Data.Odbc namespace and holds support for both local and distributed
transactions.
allows the access to database
commands, such as return data, modify data, and send data. The object Oracle client
DataReader O NET Framework Data Provider for Oracle-Provides access to Oracle data source through
object provides a high-performance stream of data from a data source. uses the System. Data.oracleClient namespace
and is contained in the
Command object to execute SQL commands. The DataAdapter object uses the connectivity software. It
resolves changes that were made to the data
The DataAdapter
object loads the DataSet with data and also System. D a t a . O r a c l e C l i e n t . d l l assembly. You must refer
both the System. Data.dll and the
Framework
in the Data Set back to the data an application that uses the .NET
the data provider and DataSet in detail source. You will learn more about System. Data.oracleClient.dll, when you compile
in the next section.
Data Provider for Oracle. It holds support for both local and distributed transactions.
Data Providers in ADO.NET 4.0-Allows the data access for Microsoft SQL
DNET Framework Data Provider for SQL Server Compact
A data
provider is a set of related components that work Server Compact 4.0 using the System.Data.SqlServerCe namespace.
together to
connecting to a database, executing commands,provide
used in ADO.NET for data in an efficient manner. It s Data Model (EDM) applications with the help of

either processed directly or and Entity Client Provider- Allows the data access for Entity
manipulated between tiers and retrieving results. The results ar the System. Data. Entity Client namespace.
data providers increase
performance without compromising on displayed after combining with
multiple sources. in
Objects of Data Provider functionality. DataSet of data based
of data and acts as the core of a wide variety
The data provider in ADO.NET
consists of the et
1S a
very useful in-memory representation of the database. The data
in
following four local copy of the relevant portions
Connection-Creates connection to the data source. objects: applications..
O DataSet can be considered as a the data in the
the database. You can load
The base class for all and updated independent of
a a set can be manipulated
Microsoft
database, Oracle database,
or
DbConnection class. The Connection the Connection
objects Is the Microsoft SQL Server
beginning a transaction. In addition, theyobject
has the methods for such as

opening and closing connection a aset from any valid source,


connection. The .NET framework have properties for Access database.
provides four types of Connection setting the timeout
property period of
which is designed classes: the Sql Connection
is
specifically to connect to Microsoft SQL Server o
designed to
provide connections to a and the 0leDbConnect ion
DdbcConnection and OracleConnection are twowide range of databases, such as Microsoft object, Wn
Access. he
other connection classes
504 in ADO.NET. 505
Date Access with ADo.NET
The
ciorn which might arise in your mind is that if both DataReade r and DataSet are used to
Chapter
12 at is the difference between the two? The answer lies in the retrieve data,
Components of DataSets DataSet are listed as
follows:
her your application should use Data Reader or Dat aSet, functionality
a
of the two. When
you should consider the type of
you decide
be used with a
table forma r functionality
components
that can
and stores data in the row
application requires.
You can use a DataSet when you want to
The various
of Dat aRow and DataCol umn
similar to a table in a databasc. You sh.'ne
data dynamically whereas yOu c a n use tne
Datakeader tor
manipulate your data, access your
O DataTable-Consists of the
ADO.NET Iibrary and
table is not no
refurnin8 your data in a forward only and read only
DataTable is the central object For example,
the
EmployeeDetails
the manner.
case-sensitive.
DataTable objects are
two
DataTable objects that have the same
note that the can contain
ADO.NET Entity Framework
employeedetails
table. A DataSet
Ihe Newkow) method is used to add
same as the values.

TableName property and different Name space property


that a DataTable c a n c o n t a i n is tixed at 21
16,7777,216. Entity Framework of ADO.NET allows you to focus on data through an object model instead of a relational
number ol rows
The maximum the integ odel. The Entity Framework allows you to write less data access code, reduce maintenance, make the structure
row to a
Dat aTable. contains collection of Constraint objects that is used to ensure
tegrity of
a
The DataTable also of data user friendly, andfacilitate the persistence of data. You can use the Entity Franework in your application
hdirectly using a new data provider called EntityClient and a new language called Entity sQL. The
data.
customized view of
DataTable for sorting, filtering searching, editing, and
O DataView- Represents a
allows you to create a
view on a
D a t a T a b l e to see a
subset of data based on a
EntityClient uses the BntityConnection and EntityCommand objects to return a DbDataReader. You
navigation. A D a t a V i e w A D a t a V i e w can be used
to present a subset canalso employ bject ervices by using either ObjectQuery object with Entity sQL or LINQ to
the R o w S t a t e F i l t e r property.
preset condition specified in Entities. You architecture of the
can see the ADO.NET Entity Framework in Figure 12.2:
of data from the DataTable.
a Datalable. A Datacolumn is the Entity UNQ
DataColumn-Consists of a number of columns that comprises
O
property of DataCol umn determines the kind
to
block of the Data Tabl e. The Data Type Query Entities Enumenbie
essential building
of data that a column holds. You can also
bind a control to particular column in the DataTable.a

its properties and


DataRow- Represents a row in the DataTable.
You can use the DataRow object and Object Servies
O
the values in the DataTable. You can use the
methods to retrieve, evaluate, insert, delete, and update
method of the DataTable to create a new DataRow
and the Add ) method to add the new
NewRow ()
Conceptual En
DataRow to the DataTable. You can also delete Dat aRow
by calling the Remove () method. Cofmmana
Model Query EntityDataReader
ree
In simple words, a DataRelation
DDataRelation-Allows you to specify relations between various tables.
is used to relate two DataTable objects to each other through DataCoulmn objects.
The relationships are

created between matching columns in the parent and child Mapping Entityclent Data Provider

columns must be the same. The DataRelation objects are contained in


DataType tables. For this, the value of both
which you can access through the Relations property of the Dataset.
a
DataRelationCollection,
Storage
Model Lomman DBDataRe ader
Typed Vs. Untyped Datasets
A Dataset can be of two types: Typed or Untyped. The difference between the two lies in the fact that
DataSet has a schema and an Untyped DataSet does not have one. A Typed Dat aSet is derived from the
Typed ADO.NET Data Providers

base
DataSet class. t uses the information, such tables, columns, and properties from the Dataset
as

Designer, which is stored in XML Schema (. xsd) file, to generate a new dataset class. This information is
an
generated and compiled into this new dataset class as a set of the main class objects and properties. The Typed
DataSet assumes all the functionality of the DataSet class and can be used with methods that take an instance
of the DataSet class as a
parameter. ataSource
The Untyped Framework
Figure 12.2: Showing the Architecture of Entity
DataSet has no built-in schema that in the Typed DataSet. The Untyped
as
contains tables and columns as in the
Datase
Typed DataSet, but the Untyped DataSet can be only exposea a The Entity Framework includes the following components:
collecti
entities that can be read in a serialized form usinga
DataReader Entity Data Model (EDM) - Defines the conceptual
DataReade r.
In ADO.NET, Data Reader is used to
sequentially read data from data that is extended express queries
in terms of to
A DataRea der Entity SQL-Defines a common SQL based query language
a source. allows
acess information a on
row single of data at
given time having a single record loaded in the
a and object ServiceS.
regardless
of the size of the result set. A Command memo EDM
Concepts. It is supported by both the EntityClient
object is required to retrieve data from the database using which is queried through a
DataReader. After creating the Command Enityclient-Provides a gateway for the queries of the entity-level queries,
object, create a DataReader
Command.ExecuteRe ader to retrieve the rows from a data source. You should use the Readby method calling common Entity SQL
language
DataReader object to obtain a row from the () or
u of LR classes. Object
results of the query. The to interact with a conceptual layer through a set
are
retrieving large of amounts
data because data does
DataReader is a good choice
not store in the cache when D e c t Services- Allows you for Entity Framework by providing services,
such as state management
also provide support
every time you finish using the DataReader memory. Call the Close () met VIces
values, they will not be available until object. This is necessary, because if identity resolution, and query building suppor
you close the Dat your Command contains re
aReader object. LINQ to Entities-Provides LINQ support for querying enties.

506 507
Chepter 12
wizards and allow develon
designers that allow
DEntity Data Model Tools-Includes command-line tools, developers to 4
Colect the Use Windows
Authentication radio button Data Access wlth
cTeate EMD applications
to model sQL Server database by using
5 Select or enter the database name in t (Figure 12.4). ADO.NET
O LINQ toSQL- Allows object relational mapping .NET Conne to a
database 8roup. Select or
enter
to query database by using LINQ, and also pe In a
Framework classes. Developers can use LINQ to SQL perform 6. the
Click the Test
Test Connect
Connection our case, we have selected the database name
combo box in the
update, insert and delete operations on database by using a programming language
supporte d by the .NE
.NET button. A Northwind database
Framework such as Visual Basic or C#.
succeeded (Figure 12.4). message bo0x
appears with the (Figure 12.4).
message Test
O WCF Data Services- Allows deploying data services
on the Web or on an intranet with
structured da . Click the OK button of the
message box, as shown in
Connecti on
data is accessible with standard HTTP protocol. Figure 12.4:
containing entities and relationships. The deployed
Enter hn o ene
Creating Connection Strings Dets soure
Similar to previous versions, the .NET Framework 4.5 provides capabilities for working with connection strings Me r e
5QL S
SCl
A connection string contains the initialization information that is passed as a parameter from the data provider e r nae

PAPUAT-PC
to the data source. The connection string is different for each of the data provider available in .NET.
The ese

connection string is parsed during an attempt to open the connection. 1he DbConnectionstringBuilder is he idon Arehc
the base class for creating connection strings. It can be used to create, edit, read, and save a connection string to
the configuration file. There are different connection strings for the different types of data sources. You can find
a list of all the available providers for creating connection strings in Table 12.1:

Table 12.1: Data Provlders in .NET


e c t er w a
da
Provider Description Ach datsb e fHe

SQL Server Data Provider (System.Data.Sqi Client) Provides data access for Microsoft SQL Server version 7.0 or
later
OLE DB Data Provider (System. Data.OleDb)
Provides data access for datasourcesusing OLE DB
Ta Connesne
ODBC Data Provider (System.Data.Odbc) Provides data access for datasources using ODBC
Oracle Data Provider (System.Data.OracleClient) for Oracle version 8.1.7 or later Figure 124: Testing Connectlon
Provides data access

8. Click the OK button of the Add Connection


EntityClient Provider (System.Data. Entity Client) Provides data access for Entity Data Model (EDM) applications dialog box.
You will notice that the data source is added in the Server Explorer window, as shown in Figure 12.5:
You can create connection string for any data provider
a in Visual Studio 2012. Let's create
string for Microsoft SQL Server by performing the following steps:
a connection Servs Bspiore
1. Open Server Explorer of Visual Studio 2012 IDE.
Dtabase Duagr ums
2 Right-click Data Connections and select Add Connection, as shown in Figure 12.3:
pnePaths
eonetions

pnt Reles
Conneteo pechenaVeons
Create tieoL Serer Database Role
pre webbventEve

Figure 12.3: Selecting the Add Connection Option


The Add Connect ion uslcmes
dialog box opens (see Figure
12.4) from where you can select the type of aaa
source that you want to attach to
your application. Note that, Microsoft SQL Server (SqIClient) is
as Data Source in the Add selectea
Change button beside the
Connecti on dialog box. You can also change Data Source by clicking ue
rodUc
Data Source text box. poen

NOTE aAaTh

When yoU Create the connectlon for the first time, the Change Data
Source dialog box comes first.
3 Enter or select the sever name of
selected GARIMA-PC (Figure 12.4).
your SQL Server in the Server name combo box. In our case, we
Added Connection in the
Server Explorer
Figure 12.5: Showing the 509
508
Date Access with ADO.N
properties of the beorated Security-Accepts two values: True and Palse. It the
Chapter 12 and press F4 to v i e w
the
data r ID and Password
value is False
then you need to specify
in the Server
ExploreI
Window
specified in the connection. If the
value is
True, then the
9. Sclect the data
source
window, as
shoWn in kigure 12.6:
accOunt credentials are used tor authentication. The default value is
True.
current
Windows
source in the Proper ties of data source is the OLEDB data
provider. You can access the SQL Server, MS Access, and
Properti5 with the OLEDB data provider. In our case, we have used the Access Oracle
tollowing connection string for MS Jet Database database and
parijal pNorthwind.dbo Conn
the MS Jet Database
Cin. You need to pass the
Eng pro de r-Mi crosoft.ACE.OLEDB. 12.0;Data source=D:\Nwind.accdb Engine
Name) Irur
The parameters of the MS Jet connection string are discussed as follows:
ueRIIAT PCIntial Catalog:iothwnd Integ ated Secuity= a Provider- Represents the type of database that you want to access
mnECtnMrng
Panyet PCParyat
ET FIamewor Data Prrnder for SCL Sernve a D a t a Source - Represents the path of the database file stored on your mac hine
Provode
oren Eor the Oracle data source, you need to pass the following connection string:
Stat
10 50 1352 Data Source=oracle91;Integrated security=ves
Versson
The parameters of the Oracle connection string are discussed as follows

a Data Source- Represents the name or network address of the instance of Oracle to which
you need to
connect.

Figure 12.6: Properties of the Data


Connection Integrated Security--Represents whether the connection is secure or not. It takes two values: Yes and No.
The Name is the name The default value is Yes.
details about the connection string in the properties window.
You can find the full
The Connect ion String property specifies For the ODBC data source, you need to pass the following connection string
of database that you have attached with your application.
data source. The Property window also specifies the Dsn=myDSN; UID=;Pwd=;
the full path of the connection string of the
in this is .NET Framework Data Provideer
In the ODBC connection string. Dsn is the only parameter passed which stores the information about your data
particular connection string, which
case
Provider for that
for sQL Server. The State specifies if the connection
is Open or Close. The Type property specifies source.
this is Microsoft SOL Server and the
you have used, which in
case
of data
the Type source

Server that is used to create data connection. The Case Creating a Connection to a Database
Version property specifies the version of SQL
Sensitive property implies whether the connection string is case
sensitive or not. In this case, the value You need connection to the database with which you want to work. In.NET, you can create a connection to the
a
the Server Explorer or code-
of Case Sensitive property is set to False. The Owner property specifies
the name of the database in two ways. You can either create a connection to the database through
to data sources, such as Microsoft SQL
administrator of the systerm, on which you are currentlyworking behind file. As you have learned earlier, ADO.NET provides access
for the different types of
Server,OLEDB, Oracle and XML. However, you need to have different connections
Syntax for Connection Strings data sources. You learn about connecting to all the three types of databases available in ADO.NET in both the
following section.
ways in the
The syntax of the connection provider. The syntax error results in a
string depends on the data
exception. After validating the connection string of the syntax, the data source opens the connection. You
run time We are going to display the data from the different
tables of the Northwind sample database. Therefore, we

can get the connection string for an OLE DB data source,


or set
such Microsoft
as by using the
Access, need to connect to the Northwind sample database.
Connection St ring property of the OleDbConnection class. For SQL Server, you
can use The
the
class the SQL Server Database
ConnectionSt ring property of the
SqlConnection to set
connection string
Connecti onSt ring property of OracleConnection allows you to get or set a connection string tor an In .NET Framework 4.5, you can connect to the SQL Server database
in two ways, through the wizard or
in which you can
ORACLE data source. The basic syntax of the connection string includes a series of keywords separatedby code-behind file. Let's create a Windows application named sQLServer Database
to retrieve the data from SQL
semicolons. The equal sign connects each keyword and its value. The value must be enclosed within the data from SQL Server in both ways. Perform the following steps
double quotation marks. The syntax of the connection string for each of the data source is different. You
retrieve
Server:
can create a connection string through the wizard, as shown in the chapter. In some cases, you can create a
a Button and two DataGridview controls to Fotml from the Toolbox and change the Text property
connection string through the code-behind file. For this, you should be aware of the syntax of the Add shown inFigure 12.7:
Or the Button control to Generate Data in the Properties window, as

for each of the data source. Let's look at the syntax of a different connection string for
connection string
each of the data source.
For the Microsoft SQL Server data source,
you need to pass the follow ing connection string:
Data
Source=GARINA-PC; Initialcatalog-Northwind;Integrated Security=True
The parameters of the SQL Server connection string are discussed as follows:
O Data Source- Represents the name or the network address of the instance of the SQL Server to which you
need to connect
Initial Catalog-Represents the name of the database.

511
510
the data
Data Access wlthAADO.NET
Chapter 12 1 Select Database as source
type and click the Next
button, as shown in
1AM 9
Figure 12.9:
engC gn

an tu

Cembed n M 0
DerTme

het Flgure 12.9: Selecting Data Source type


The Choose a Database Model page appears (Figure 12.10).

4Select Dataset as the database model in the Choose Database Model


a
page (Figure 12.10).
5. Click the Next button, as shown in Figure 12.10

Figure 12.7: Adding Controls to the Form


In the first grid, we generate data through wizard and in the second, we generate data through code on the
Click event of the button. Let's first generate data in the dataGridViewl control through wizard by
pertorming the following steps

2. Select the dataGridViewl control and click its Smart Tag


Click the Add Project Data Source link from the Choose Data Source drop-down list in the
3
Smart Tag of the dataGridViewl control, as shown in Figure 128:

KOKT A oRG TAM MAT TOOS TEST RCHTICEANALYZ WOOW

*|
tandiewl Syaea Wndew

eDa Flgure 12.10: Selecting the Database Model


dataGridvienl

E ies The Choose your Data Connection page appears (Figure L2.11).
Acce DeuA
6. Click the New Connection button in the Choose Your Data Connect ion page, as shown in

Ala Fab
Figure 12.11:

ep le
*

Foed ange

EnablNahAosder
Paned

Figure 12.8: Adding Data Source


The Data Source Configuration Wizard gets displayed (Figure 12.9).
Figure 12.11: Selecting Data Connectlon

512 513
Deta Access with
Chepter 12 Des Seurce Confgunticn Werd AD0.NET
The Add Connection dialog box appears. o Tour
section of this chapter.
Detnbase Objert
the Creating Connection Strings
7. Create the connection string as explained in Which detabese ooects
is shown in the drop-dow
drop-down list
do you wet
notice that the path of the data base myeu datase?
After creating the connection string, tegones
(Figure 12.12). CutemeCutome0
12.12: emerbemogphics
8. Click the Next button, as shown in Figure Cnome

Di Sre C m Order Detads


Your Dete Connectien

Shionen

uppliery
eonies

Functions
A ur he edom.atn ben t ode DotaSet name
NerthwindDtus

pkon (epend te see dieik)


enecbos png thel yw

Figure 12.14: Selecting Database objects


The Data Source Configuration W1zard is closed and you are taken back to Windows form. In the
Windows form the datadridViewl control is now bound to the Customers table.
mms J t ne You can see that cust omersBindingsource and customersTabl eAdapter are automatically added. You
can preview the data before running the program.
Flgure 12.12: Displaylng Data Connection
The Save the Connection String to the Application Configuration File page appears (Figure 12.13). 12 Select the Preview _Data linkfrom the Semart Tag of the dataGridViewi control The Preview Data
dialog box appears (Figure 12.15).
9 Clear the Yes, save the connection as: check box and click the Next button, as shown in
Figure 12.13: 13. Click the Preview button, the data is displayed in the Results section, as shown in Figure 1215:

PreviewData
Connecton Seing to the Applicaton
Seve Confgurs ten Fl Select an objJect to previe

NorthwindDotaSet.Custormers.FiL GetDta 0
No parameters are defined on the selected ooec
connt n th in e Dataaet

Netdometnrg

esuts:

CustOmenD CompayNome Contacinieme Contaclde Adde y gjon


ALFK Areds er..Mana Andes aes Kepresent-0bere s. S em
Ana Truulo Em.. Ana Truytlo O Can-Meco D..
ANATR
ANTON Antonio Moren Antonio MorenoOwner Mazaderos 2512 NMerco U
AROUT Around the Hom Thoms HerdySs Represent 120 Renover 4London
BERGS Degunas snab-|Chrstina Begl |ordes AdmunestBerguyigenLulel
Mannhem
BLAUS Moos skgrsetosteri. MaNnem
Prev BUer See Det-Henna
BLC Blondesddsi pe- Frédenque Cte. Mrteting Men-2, pace uebe S0oUg
Bohdo Comida.. Martin Sommer wn ARqu O Mn

Figure 12.13: Saving the Connection String BOUD


The Choose Your Laurence Lesn e 12 rue des BouMarsee
BONAP
Dat abase Objects page appears (Figure
12.14 BOTM Bottom-Dolarlzabeth Lincoln Accounting
Tawan
Ma-3Taasen snassn
10. Select the tables
you want to unbeoy Gns London
Customers table
display in the Dat aGridView control. In our case, we have selectE
the BSBEV sBevereges Victona Ashwof.is Kprser
(Figure 12.14).
11. Click the Finish button, as shown in Figure 12.14: Columns: 11 Rows9
Data
the Preview of the Retrieved
Flgure 12.15: Showing

514 515
control fror
Data Access with ADO.N
Chapter 12 accessing
data in the
DataGridView

o u da F Forml
most-convenient way of the code-behind file. For this
and the control using te the
This w a s an easy
the data in
the
DataGridView

Forml by double-clicking
double-clicking it,
it. No
Now, add the
o n the
source. Now, let's access

that we have added


control
of the But ton file:
C l i c k event code-behind UustomerlD CompenyNene
to the CutomAD
shown in Listing 12.1, operyae
highlighted code code-behind file ALFK reds Futeride
mekae

12.1: Showing
the Code for the ANATR Pna Inglo Epa ANAT
Listing ANTON Moreno
using System; Arton ANTON rtonin Mren
usTng system.collections.Generic; AROUT Around the Hom APOUT Aound the Ho
I
ComponentMode BERGS Bernds a BEPGS
Using system. ab
Bauer See Delk
using System.Data
Using 5ystem.bata.sqiclient;
BLAUS BLAUS Bla Se Dk
BLONP Slondesddsl père BLONP ndesdd Dre
using System.Drawi ng;
BOLD Bókdo Comdasp BOuD o Comdas p
USing System. Linq
BONAP on
app BONAP Bon
using 5ystem.Text; Tasks; BOTTM Botom-Dolr Ma. BOTTM Bott om-Dolar Ma
using System.Th reading .
using System.Windows. Forms; BSBEV BSBEV

namespace sQLServerDatabase CACTU Cacus Comda CACTU Cachs Comda


CENTC rtro comeroa cENTC Certro comers
Form
public partial class Forml : HPS
hn

public Form1()
Figure 12.16: Showing the SQL Data in the DataGridView control
TnitializeComponent OLEDB Database
Microsoft for accessing different types
private void Form1_Load(object sender, EventArgs e) OLEDB is an Application Programming Interface (API) designed by
Server, or even an Access file. ln
of data stored in different formats. It can be used to access Oracle, SQL
1/ TODO: This line of code loads data into the 'northwindpataset.Customers OLEDB. In .NET 4.5, you can connect
table. You 1t,
this section, you leam to connect to the Aacess database file by using
can move, or remove as needed. to the Access database in two ways, through
the wizard or code-behind file. Let's create a Windows
this.customersTableAdapter.Fi11(this.northwindbataset.Customers); can retrieve the data from the Access file in both ways.
application named OLEDBDatabase in which you
from the Access file:
Now, perform the following steps to retrieve the data
Add a Button and two DataGridView controls to Forml, as we did in the preceding section.
void
private buttonl_click(object sender, Eventargs e)
2. Select the dataGridViewl control and click the Smart Tag to select the content
for the dataGridViewl

Sqconnection connection new Sqlconnection) controi.


list in the
connection.ConnectionString = from the Choose Data Source drop-down
3. elect the Add Project Data Source option
Paa SourcesGARTMA-PC;Initial cataiogeworthwind ntegrated security=True" control. The Data Source Configuration Wizard appears.
connection.openO;
Smart Tag of the dataGridViewl
Choose DatabaSe
open the
a
button to
Sq ]DataAdapter adp =
new
sqlDataAdapterC"select from Customers" elect Database as the data source type and click
the Next
Connection); Model page.
Dataset ds new DatasetO the Next
Choose a Database Model page and click
. Select Dataset as the Database Model in the
adp.Fil1ds); button to open the Choose your Data Connect1on page.
dataGridview2.Datasource ds.Tables [0]
New Connection button in the Choose Your Data Connection page. 1he Add
.Cick the
Connection dialog box appears (Figure 12.17).
12.17:
as shown in Figure
ick the Change button of the Add
Connection dialog box,
NOTE
Ou shouio change the connection
System.Data.SqlClient namespaces instring
in the
code and make 1 to add
i according to
the your system. YOu also do
Formi.CS page.
Now, run the
application by pressing the F5
Data button, is as shown in key. The output of the
application, after nerate
Figure 12.16: clicking the
Gee

516 517
Data Acces wlth
Access database and click the
ADO.NET
Solect an Open button. In our case, we have selected the Nwind
Chapter 12
0.

shown
in Figure 12.20: database, as

te

Mcee ee

1321pa

'

amachdat Figure 12.20: Showing the Select Microsoft Access Database Fle Dialog Box

11 Click the Test Connection button to test the Access database connection you Connection
have created. As you click
the Test Connection button, a message box appears with the message, Test succeeded
(Figure 12.21).
OK button of the message box, as shown in Figure 12.21
12. Click the
12.17: Showing the Add Connection Dialog Box
Figure
dialog box appears (Figure 12.18).
d p

The Change Data Source

File data source and click the Ok button, as shown in


Access Database
8. Select the Microsoft
Figure 12.18:

cten

he the selexton to connet to s

Mcresct ALces dalabesr


me-crt Daa Prarde For
McecSo N

ET Fene Ota orOLE Flgure 12.21: Testing Connectlon


box.
13. Click the Ok button of the Add Connection dialog box to close the dialog of the
Wizard. Notice that the name
Source Configuration
Figure 12.18: Selecting the Data Source You have been redirected to the Data
database is shown in the drop-down
list (Figure 12.22).
After selecting the data source, the Add Connection dialog box reappears (Figure 12.19).
shown in Figure 12.19: 14. Click the Next button, as shown in Figure 12.22
Click the button to browse the location of your Access database file, as
9 Browse

Add Connecton

n r inommton to connect to the elected data Lource or chck


Cg t hessea dheeri dta bource ender piDnde.

r o o N ACcess DEabae e (OLE D5)

Log an to the dmabase

Uher nane Adma

LE y pesou

Advanced.-

Tea Conedaen
ance

Figure 12.19: Clicking the Browse Button Data


Connection

12.22: Displaying 519


Flgure
The Select Microsoft Access Database File dialog box appears (Figure 12.20).
518
Data Access with ADO.NET
Chapter 12 database to your application (Figure 12 23
.23). The Data Source contiguration Wizard is closed.
a local file of the
A message box appears
asking you to copy as shown in Figure 12.23; Cinished, you will be taken back to your Windows form with the
application, once
to copy the
data file to your
the Employees table. The dataGridViewl control now
15. Click the Yes button
eft Viu Sdi
employeesBindingSource
and
boun ally get added in the application. You can preview the data before employee
sTab leAdapte r
The cennert
s a loca! dats file that s net in he

lk to copy the fle to your proyei ana h


S
e Preview Data link from the Smart Tag of the dataGridViewlrunning the program.
therermetven?
19.
dialog box appears (Figure 12.26).
control. The Preview Data
projAT
pretct
a be
wi copd te the
Tev eyou"
sa te
Wyou
y o u cepy
ey heo u un the apphczton Pres 1 for
1ick the Preview button, the data is
op rehng thn behe displayed in the Results section, as shown in Figure 12.26:
Previw Dea
SMet an e d e p e

PhwindDetrsetEpynkGAD*s

Figure 12.23: Showing a Message Box


Connection String to the
ApP11 cation Confiqurats
ation
the
This redirects you to the Save

File page (Figure 12.24).


as: check box of the Save the Connection Strina Fitiam
connection to
16. Clear the Yes, s a v e the
the Applicati on Configuration
File page and click the Next button, as shown in Figure 12.24 e lency

e 8/D1

en
Save e Ceerden Sirig Applkatien Cotgure ten Fie

Dedth
Enne
Yee en

Cekm 17 Pes]

Figure 12.26: Previewing Data


in the DataGridView control In the same
In this way, you can view the content of the Access database
file.
retrieve the content of the database in the DataGridView control through code-behind
way, you can which is
Let's add the code in the application to access the data in the second DataGrid7iew control,
added to your application. For this, add the code, shown in Listing 122, on the Click
highlighted
Figure 12.24:Showing the Save the Connection String to the Application Configuration File Page already
The Choose Your Database Objects event of the Button control:
page appears (Figure 12.25).
Control
17. Select the table you want to
display in the DataGridView control. In our case, we have selected the Listing 12.2: Showing the Code for the Click Event of the Button
Employees table (Figure 12.25). using System;
18. Click the Finish button, as shown in Figure 12.25: using system.collections.Generic
using System.ComponentModel;
using System.Datta;
Y Debase Ojects using System.pataoleb
Using system.Drawing;
using System.Ling;
using system. Text
te using system.Threading.Tasks;
using system.wi ndows. Forms;
namespace OLEDBDatabase

public partial class Forml: Form

public Form1)

InitializeComponentO;
Figure 12.25: Selecting Database sender. EventArgs
objects private void Form_Load (object
520 521
Data Access with O.NET
Chapter 12 Employees the
drive ot system with the rname
the system Bookl .xlsx. You need to
table
nwindbataset.

code 10ads data 1nto


the
the D: h i l e creatin
while
creating the connection string. provide the right path of the Excel
This line of needed. ource

// it, as
TODO: can move, or r e m o v eFil1(this.nwinddataset.Employees): Data
this.employeesTableAdapter. file in
YOu
the code,
shown in Listing 12.3, to the Click event of the Button control:
Add
4. Showing
Listing 12.3: Showi the Code for Click Event of the Button Control
EventArgs e)
sender,
button1click(object

private void ng System;


using System. Col1ections.Generic.

olepbconnectionO0
oTebbconnection con= new using System. Componen tModel;
Con.connectionstring using System. 0ata;
CProvider=Microsoft.ACE.OLEDB. 12.0; Data
using system.Data.0lepb;

from Employees",
Source=|DatapirectoryI\\Nwind.accdb")

olepbDataAdapterC'select on) orawing;


01epboataAdapter da= new using System.
Os using System. Ling
Dataset ds new Dataset Text;
da.Fil1(ds); using 5ystem.
datacridview2.Datasource=ds.Tablest0] using System. Threading. Tasks;
wi ndows. Forms;
using System
.

namespace oLEDBEXcel

class Forml : Form


public partial

NOTE connection string in the code and make i according


to your system. You also need to adh public Form1()
You should change the
in the Form1.cs page.
System.Data. OleDb namespace Initializecomponent();
Data button is shown in Figure 12.27:
application, after clicking the
Generate
The output of the sender, EventArgs e)
private void button1_Click (object
string connectionstringe
"Provider-Microsoft.ACE.OLED. 12.0;Data source-DNBookl.x1sx;EKC

bOOyeeD
12.0;HDR=YES" olepbconnecrion(connectionstring)
0leDbconnection ExcelConnection new
volo
Davolc
oleDbDataadapters adapter-ner olepbData dapterO:
adapter.selectcoand=ne olepbcommand
Fescoos "SELECTFROM [COntactss],EXGeIConnection)
Buchanan
DataTable dt=new DataTable0%
Suyane
adapter.FE11dt)
dataGridviewl.oatasourcedt

Dod o

DataGridView control at
view the data of an Excel file in the
In the code Listing 123,
given in ycu can
after the click of Click to View Data

DB. You can see the output


the click of Button, using OLE
utton, as shown in Figure 12.28:

Figure 12.27: Accessing Data in the DataGridView Control Foml

As stated earlier, the OLE DB can also be used to access other types of data source, such as an Excel file. You can
use OLE DB to retrieve the data of an Excel file toa DataGridView control. Let's create another example to see
0
2915420 Tegoh
415
how you can retrieve the data of an Excel file in the DataGridView control
by performing the following steps 734685531 D
415 2 0 0 9 A11 500

213-915
1. Create a Windows Fornms Application named OLEDBExce l in Visual Studio
2012 807 91664
415
3019648531A
6583N
Add a DataGridView control anda Button control to Forml.
Change the Text property of the Button control to Click to View Data.
41S
34219 S40 ClgN
Dn S
The data in the DataGridview control is retrieved when you cick the Button control. The Excel fie
27809191

515454 01 L2-075 67 Seen


used in the DataGridView control is a simple Excel 2010 file with some data in it. We have created u 8462035
Excel 2010 file and entered data in it. This file has columns with the
Emp_Number, Emp_Address, and Emp_Salary. The sheet of the Excel file has been Emp_Na
name Emp_ID,
Flle Uslng OLE DB
renamed from an Excel
the Record
Contacts. After entering the data in the Excel file under these 12.28: Dlsplaylng
columns, we have saved the Excel nle Flgure
523
522
Chepter 12
ODBC Data Source name in the ta Source Name text box Data Acces9 wlth
ODBC is the interface for accessing data in a heterogeneous environment of relational and non. ur case, we have entered myDSN as
of the ODBC
Data Source Name (Figure Microsoft Access Setup ADO.NET
database management systems. The best example of using the ODBC data source is accessing a Microsafona Click the Select button in the
Database group, as 12.31). dialog box. In
5 shown in
database. You can create an
ODBC data source through the wizard as well as the code. An oDBC Useess Figure 12.31:
source should be created before creating an ODBC data source. This User data sour ce stores info data
about how to connect to the specific data provider. You need to keep in mind that User data nformation
ource is only
visible to you and can be used only on your machine. Let's first create an oDBC User data souron
performing the following steps: urce by
1. Open Control Panel and open Data Sources (ODBC) from the Administrative Tools.

NOTE
The ProgramData folder is a hidden file that would not be displayed unless you select the Show
Hidden Files ah
Folders option. and Figure 12.31: Showlng the Access
The Select Database dialog box appears (Figure 12.32).
Setup
The ODBC Data Source Administ rator
dialog box appears (Figure 12.29). to the database file stored on
2. Click the Add button in the User DSN tab of the ODBC Data Source
Administrator
6. Navigate Access your machine from the Di rect ories
list box. The name of
shown in Figure 12.29: dialog box, as the selected Access file appears in the Database Name list box
(Figure 12.32).
7. celect the file in the Database Name list box (in our case we have selected
Nwind. accdb) and click the OK
button, as shown in Figure 12.32:
OSStn DSN R DSN Dhvem|Taarg Conmecion Pocing |Aboud
Dta Sau
SASE FR
det
MS e c Dsabene

D e o t Aeos De (Cmdb. 'acab)

oDBC oUe D omsonbo ho to conecdio


denoy ee ory v o e to yau
Figure 12.32: Showing the Select Database Dialog Box
The Select Database dialog box is closed.

Figure 12.29: Creating User Data Source


8. Click the OK button of the ODBC Microsoft Access
source added to the ODBC
Setup dialog box. Youcansee that the myDSN data
Data Source Administrator dialog box (Figure 12.33).
The Create New Data Source
dialog box is displayed (Figure 12.30). . Click the OK button on the ODBC Data Source Administrator dialog box, as shown in Figure 12.33:
3. Select Microsoft Access Driver in the
Create New Data Source
button, as shown in Figure 12.30: dialog box, and click the Finish

Crete Ne Data Saur

e tor honntto epa dte suroe


Nae

e p e e Morsot Vas FexAro

o o t Aces Devec

Cactges Dr cdb}

Data Source
Flgure 12.33: Showlng the Added
and attach it to your application.
the ODBC data
source

C
The d source is created and you can use
attached to it. For this, create a Windows
ODBC data source
Flgure 12.30:
Now et's r e a t e an application with the Button cono
controls andn a Figure
t

Selecting Driver for the New Data Source applic named ODBCData Source and add two
DataGridView
Data, asshown
l*

The ODBc Microsoft


Acce ss Setup dialog box appears (Figure 12.31). Ch n Click to Generate

e t e x t of the But ton control to


525
524
Chapter 12
The Change Data Source dialog box
appears (Figure 12.36).
Data Access with AD0.NET
6.
she Mi crosoft ODBC Data Source
and click the OK button, as shown in
Drarare
Figure 12.36:
Acrms Dem

Ds pre

Flgure 12.36: Changing the Data Source to ODBC Data


Source
Selecting the Data Source, the Change Data Source
dialog box closes and the Add
box appears (Figure 12.37). Connecti on dialog
17 Select the data source myDsN rom the Use user or
system data source
(Figure 12.37). name
drop-down list

18. Click the OK button of the Add Connection


dialog box to close it, as shown in Figure 12.37:
Figure 12.34: Adding Controls to
Form
We will generate the in
DataGridView control
data the first DataGridView control
at the click of the Button. Let's first
through the wizard and in the second
data in the first
generate DataGridView control
through the wizard.
10. Select the dataGridViewl control and click the Smart
Tag to select the content tor the
dataGridViewl
control.
11. Click the Add Project Data Source link from the Choose Data Source
drop-down list in the Smart
Tag of the dataGridViewl control. The Data Source Configuration Wizard appears.
12. Select Database as the data and click the Next button to
source type open the Choose a Database
Model page
13. Select Dataset as the Database Model in the Choose a Database
Model page and click the Next
button to open the Choose your Data Connection
page.
14. Click the New Connection button in the Choose your Data Connection page. The Add
Connection dialog box is
displayed (Figure 12.35). Flgure 12.37: Specitying Data Source
the data base is shown in the drop-
15. Click the Change button of the Add Connection
dialog box, as shown in Notice that the data source is attached to your application and the path of
Figure 12.35: down list (Figure 12.38).
19. Click the Next button, as shown in Figure 12.36:

e Yeer D e Cens

Figure 12.35: Showing the Add Connection Dialog Box 1238: Showing
the Data
Connection
527
Figure
526
Chapter 12 Date Access with ADO.NET
ration File p the Preview Data link from the
Smart
Application
Configuration
page appear Tag of the
dataGridViewl control. The Previ
Connection
String to the OX appears. When you click the Preview eview Data
The Save the button, the data is
(Figure 12.39). do not want to save the connectios
shown in Figure 12.41: displayed in Results section, as
connection as: check bOx, It yOu n in a
the
20. Clear the Yes, save
default (Figure 12.39).
The check box is
selected by t e p
connection string.
shown in Figure 12.39
Click the Next button,
as
21.
qurtier

aVe ennedoon Suin9o PPe Don Conngunbon

To w e Ue

yeu appletien coniguten


e eres
menienance m dpiymet CReg Qua en
in in
erter* name h e n ciece N e r
t e bon and
cnection tring in the applcetien configurtion file, s06 1800

Yex tae the cewnectisn Chd Antrer

CheAnton rG
andrat Be

-1 n
ertheod

Figure 12.41: Previewing Data


In the same way, you an retrieve the content of the database in the DataGridView control through
Pres ancE
code. Let's add the code in the application to access the data in the second DataGridView control, which
Flgure 12.39: Saving Connection String is already added to your application. For this, the first step of accessing an Access databasethroughthe
adding the namespace, add the
The Choose Your Database objects page aPpears (Figure 12.40). ODBC data source is to add the System. Data .Odbe namespace.
file.
After

22. Select the table you want to display in the DataGridView control. In our case, we have selected the highlighted code shown in Listing 12.4, to the Forml.cs
file:
Products table (Figure 12.40). Listing 12.4: Showing the code for code-behind
shown in Figure 12.40: using System;
23. Click the Finish button to close Data Source Configurat ion Wizard, as
using System.collections.Generic;
Data Seurce Canligunton using system.ComponentMode1;

C p o Vour Dembaee Objec


using System.Datta;
USing System:Data-odbcs
using system.Drawing;
USing System. Ling;
Converson Erors using System.Text;
uSing System. Threading.Tasks;
Oser Deah
using System.windows. Forms
Products namespace ODBCDatasource

Soppen
Form
public partial class Forml:
A Funcuons
a
9 public Forma
Detabet name

Dtasel
Initializecomponent O;
sender, EventArgs e
void FormLoad(object.
Prenous private d a t a s e t l . products'
table. You
the
TODO: This 1ine
of code loads data into
7/ it, as needed.
Figure 12.40: Selecting the Products Table or
this.productsTableadapter.
can move,
remove
Fi1l(this.datasetl. Products);

he datasetl,
product sBindingSou rthece and productsTableAdapter are automatically added to Formi. EventArgs
e
You can
preview the data before
running program. void
button2_click(object
sender,
private
Odbcconnection connection=noed
w bcconnectionO

529

528
Chapter 12
connection.connectionstring Dsn=myDSN;UID=PWd=
String sQL select from Products"
using System. Drawing; Date Access with ADO.NET
using System. Lin9;
connection.open ) using system. Text;
connection)D
odbccommand CsQL
odbccommand cmd
new
QdbcbataReader dr CHd.ExecutereaderO using System. Threading.Tasks;
Dataset ds = new Dataset O using system. windcws. Forms;
namespace Commandobject
Datarable dt new DataTableC"Products")
dt.Load(dr) public partial class Forml1
ds.Tables.Add(dt); Form
datadridview2.AUtoGeneratecolumnstrue
public Form1()
dataoridview2.Datasource dsuTables [0J
Gonnection.closeO
dr.close0 InitializeComponent (0:
Cmd.DisposeO%
connection.DisposeO private void FormlLoad (object sender, EventArgs e)
sqlconnection connection new sqlconnectionO
connection.connectionstring "Datasecurity-True":
Catalog-Northwind ;Integrated source-GARIMA-PCInitial
The output, after clicking the Click to Generate Data button, is shown in Figure 12.42: connection.open)
sqicommand cmdnew sql
sqloataAdapter adp newcommand("selecCt from Employees" connection)
sq1patadaptertcn)
Dataset ds = new Dataset0;
L OsKto ete Das
adp.F111(ds, "Employees")
ProuctID adua
ON
ComboBox1.Datasource ds.Tables["pioyees"1:
Oun comboBox.Displaymember"EDloyeep"
Arneeed
O t
comboBoxl1.valueMember "Empoyee1o
Gardra

Nortwesr

h
10
NoTE
You need to modity the value of the ConnectionString property according to your computer configuration. You need to
addthe System.Data. Sq/Clientnamespace inthe Form1.csfile.
Figure 12.42: Showing the Output of the ODBCDataSource When you
Application execute the code by pressing the F5 key, you would find that comboBoxl has values in it
code m
field values of the Employee table. The output of the
Creating a Command Object These values are the EmployeeID
Listing 12.5 is shown in Figure 12.43:
After establishing connection to a data source, you can execute commands and
a
data source using the return results from
DbCommand object. Each NET Framework
data provider has its own
tne Foml
object that inherits from the DbCommand commanan
object. For example, the data provider for OLE DB includes Selet Eployes D
oledbCommand object. The data
provider for SQL Server includes the
provider for Oracle includes the OracleCommand SqlCommand object. The daa
Commandobject, to demonstrate the use of Command object. Let's create an application, nant
object. In this
object. For this, you first need toapplication,
SqlCommand object to create a command we have usea
u
and a ComboBox named add a Label named
Label control to Select
comboBoxl to Forml. After
that, you need to change the Text lane
Employee ID. The
Employees table ot the Northwind database. comboBox1 will display the Employee ID rOn the
propertyo
After adding the controls to Combo Box uslng the Command object
shown in Listing 12.5, on the Load event your form, add the cou Figure 12.43: Retrieving Data in the
of Forml
Listing 12.5: Showing the Code for the Load Event in the Forml.cs file: Working with DataAdapters
of the Form1
using system; and DataSet. This means
data between a data source
using System,collections.Generic a r e a set of objects used to exchange
S DataSet and writing thechanged
that na data from a database into a
using System. ComponentModel; is responsible for reading
as follows
using System.Data; data frons ter DataAdapters in a NET Framework are
database. The available
Dataset the
to
Using System.Data.sqlclient OLE DB provider
data
work with any
exposed by the
source
dAdapter-Allows you to
530 S Server
SqlDataAdapter-Works only with SQL 531
Chapter 12
from the Orders table of the Data Access with ADO.NET
OOdbcDataAdapter- Allows you to access an ODBC data source The
and
he
click Gene rate D
t h e Generate Data
at: Northwind
button, you can see the database. W'hen
a
OracleData Adapter-Works with Oracle database
key,
output, as shown in you run the code, by pressing
ing !F5
Figure 12.44:
Now the question arises that how can we the DataAdapter in the et's try
application. Let's
use
try and
and aanswer
this question in the examples that follows.
NET
Creating DataSet from DataAdapter OMSP
HAUR
DataSet are the objects that contain
data tables where you
can temporarily store the data. The
does not depend on the data soure and the interaction with existing data sources is controlled throta
Data. SUPRD
HANAR
the You can load the DataSet er. The
DataAdapter. by using DataAdapt SelectComma nd
the DataAdapter is a Command object that retrieves data from the data source. You can also us
properh OPS
InsertCommand, UpdateCommand, and the Delete Command properties of the the WELD
DataAdapter
manage any updates of data in the data source. You can use the Fill () method of the DataAdapter
11E
o
load the data that is retrieved using the Select Command, in the DataSet. Let's Figure 12.44:
create Generatlng Data on Clicking the Button
named Data Set from Dat aAdapters, to create a DataSet from a DataAdapter. Addapplication.
an
a
control and a DataGridView control and Button Paging with DataAdapters
change Text property of the Button control to
Data. Now, add the highlighted code, shown in Listing 12.6, on the Click Event of the ButtonGenerate i n ADO.NET is the process of
returning the results of
control query in smaller subset of data or more
a
Listing 126: Showing the Code for the Click Event of the Button Control sDecifically pages. YOu can use tus practice for
displaying results in small and to
using System; The Data Adapter provides a tacility for returning only a page of data. The easy manage chunks.
DataSet with only the requested records. You need to use the startRecord Data Adapter fills the
using System.collections.Generic; parameter to return the first
using system.ComponentModel; cord in the page of data, and the maxRe co rds
parameter for the number of records in the page of data.
using System.Data Let's create an application, named PagingData, where you
Using System.Data.sqiclient; can apply paging of data with DataAdapters.
Add a Button control and a DataGridView Control and change the Text property of the Button
Using System.Drawi ng;
using System.LUngi control to Load Page. Now, add the highlighted code, shown in Listing 127, on the Ciick event of the
using System.Text; Button control:
using System. Threading.Tasks; the Code for the Click Event of the Button Control
using System.windows. Forms Listing 12.7: Showing
namespace Dataset fromDataAdapters using System;
public partial class Forml Form
using System.col1lections.Generic
using System.ComponentModel;
using System. Data;
public Forml()
sing System.Data.sqlclient
using System. Drawing;
InitializeComponent(); using System. Ling:
private void button1Click using System.Text;
(object sender, Eventargs e) using System.Threading.Tasks;
sqlconnection connection new sqlconnectionO
= using System.windows. Forms;
connection.connectionstring "Data Source=GARIMA-PC;Initial namespace PagingData
catalog=Northwind;Integrated security=True"
Connection .openO public partial class Forml Form
SqloataAdapter adp new Sqlpataadapter
"select *
from orders", connecetion)s public Forml()
Dataset dsnew Dataset 0:
adp.Fill(ds):
datacridviewt.Datasource ds:Tables [0] InitializeComponent (0:
sender, EventArgs e
void button1_click(object
private
int pagesize3 new Sqlconnection Q:
NOTE
You need to modily the value of the
S
coqn
icno
encn
t ie
o cn
t.ic
oonnconnection=
nectionstring ="Data Source-GARIMA-PC;Initial
Security=True"
ConnectionString property according to your computer configuration. You neeu catalog=Northwi nd;Integrated
add the System.Data. Sqlclient
namespace in the Form 1.cs file. connection.open C0 pagesize
string ordersQL "SELECT TOP
FROM orders oRDER BY OrderID" 533
532
Chepter 12
sq1DataAdapter(ordersQL, connection): namespace updatingData Deta Access with
dEsqlDataAdapteradapter
new
ADO.NET
DatASEr Dataseta new DatasetO
dapter.Ei1Dataset orders") pub1ic partial class Form1 Form
datacridviewL.Datasource=Dataset Tables["orders"]:
publie Form1()

InitializeComponent();
private voíd
NoTE to your computer configuration Y
FormlLLoad (object sender, EventArgs e)
the value of the ConnectionString property according
You need to modity need to // TODO : This 1ine of code loads
add the System.Dala. SqIClient namespace in the Form1.csfie. datait,into
table. YOu can move, or remove the
'northwi nddataset.customers'
this.customersTableAdapter. Fill (this.northwineeded.
as

When you run the application and click the Load Page button, you
can see that
only five recorde at nddataset.Cus tomers):
Orders table are loaded. The pageSi ze variable specifies the amount of data to be loaded to void
DataGridview control. The output of the application after you click the Load Page button is sho
private button1Click(objject sender, Eventargs e)
nown in
Figure 1245: customersTableadapter.update Cnorthwindpataset

As vou have already learnea that the


custome rsTableAdapter and the
NE
obeli

415 &1/1
northwi
automatically generated when you create the data source connection through the wizard
nd Da taSet are

ANAR
When you run the application, the original table is generated in the DataGridView control. You can add
19 &6 19
a whole new row in the Da taGridVi ew control while the application is running, and then click the
Update Dat. button. The new data is added in the DataGridView control and data source. You can
see the output of Forml, atter pressing F5 and entering the new record in the DataGr idView control, in
Figure 12.46:

Formi
Figure 12.45: Displaying the Data After Setting the Page Size of the DataGridView control

Updating with DataAdapters OlonerD

You can update a data source with the help of VINE


DataAdapter. The Update () method of the DataAdapter WAOR DWardnde R S Ror
is called to resolve changes from the DataSet back to the data source. When Wn R P Keb krirg Nrag
you call the Update ( WARTH
method, the DataAdapter analyzes the changes that have been made and executes the command. When weu
the DataAdapter encounters a
change to a DataRow, it uses the
WHITC
wteCrv-
UpdateComnand to process the change WILMK Wan Kle Ken O/ng
You must note that the Update () method is
performed on a row basis. When an application calls the WOLZA W 2ad Ae

Update () method, the DataAdapter examines the RowState and executes the
property
O Admro

NSERT, UPDATE, or DELETE statement for each Let's create an


required
you can update the data with DataAdapter. For this, you
row.
application, UpdatingData, wherea
first need to add a Button and
DataGridView control to Forml. After that,
you need to change the Text property of the Button Flgure 1246: Updating Data at Runtime
control to Update Data and add the project data source to the DataGridView control
wizard as shown in the section
through tne
Creating Connection to a Database of the chapter. After adding the aaa
a
Adding Multiple Tables to a DataSet
source, add the highlighted code, shown in DataSet and add different
Listing 128 on the Click event of the Button control: contain multiple tables. You need to create a single
Listing 12.8: Showing the Code for the Click Event of the 2ngie DataSet can
controls in your application.
Let's create an application, named
Button Control
aDles to different
DataGridView
with a single DataSet. Now, add
system;
in which you can add multiple tables to your application the text of both the
using System.collections.Generic; tltable, controls to Forml. After that, change
DataGridView controls and two Label the code, shown in
using System.componentMode1; O Table and Orders Table, respectively and add
using System.Data;
T COntrols to Order Details
using System.orawing: Listing 12.9, on the Load event of Forml:
using System.Linq4
using System.Text ;
using System. Threading.Tasks;
using System.wi ndows. Forms; 535
534
Date Access with
ADO.NET
Chapter 12 of the Form1
the Load Event
Code for
Showing the
Listing 12.9:
using sys tem;
u s i n g s y s t e m . c o l l e c t i o n s . G e n e r i c ;

System.componen tMode 1; 14

using
using system.bata
Using systen.Data.sq1client

Using system.Drawing;

using System.Ling
using System.Text
Tasks;
using System. Threading.
FormS;
Using System.windows.
namespace Multitable

class Forml: Form Flgure 12.47: Showing Multiple Tables


public partial
pub1ic Form1) Creating DataView
a snapshot of the data in a table and work with it. DataView is same as a
Vou can use DataView to get
InitializeComponent ); read-only mini-DataSets; you typically load only a subset of a DataSet into a data view. A DataView
e)
private void FormLLoad(object
sender, EventArgs
ro A ovides
provi
a dynamic view of the
It provides
data. a DataRow array from a table based on a particular filter
and filtering criteria with the help of DataView. Let's create
sQlconnection connection=new sq1ConnectionO or sort order. You can apply different sorting and view your data. Add two Button anda
connection.connectionstring "Data
source=GARIMA-PC; Initial an application, named DataViews, in which you can sort
Catalog=Northwind; Integrated security=True and change the Text property of the buttonl and button2 controls to Sort
DataGridView control
in
Mexi co, respectively. Now, add the highlighted code, shown in Listing 12.10 in
onmection.open by City and Only
ataset dsnew Dataset0 the Forml.cs file:
sqlDataAdapter adp new sqloataadapter(
connection the Code for the Form1.cs File
s e l e c from [order Details]" Listing 12.10: Showing
Rdp.Flds, [order Details]); Deeusing System
Details1"];
atacrtavievl.Datasource ds.Tabies ("torder *
from Orders, connection);
using System.collections.Generic;

sq1DataAdapter adp1 new sqlDataAdapter("select =


using System.componentModel;
dl.Filds,orders") using System.Data;
ataGridvie2.Datasource dsTables["orders"] using system.Data.sqlcient
using system.Drawi ng;
using System.Ling:
using System.Text;
using System.Threading.Tasks;
NOTE You need 0
using System.wi ndows. Forms
need to
You ConnectionString property according to your computer configuration.
modify the value of the
add the System.Data.SqIClient namespace in the Form1.csfle. nemespace Dataviews

You can display multiple tables using a single DataSet by first creating a connection. After that, you public partial class Form2
Form

need to add a DataSet to your application named ds. In addition,


you require creating
SqlDataadapter named adp for the first DataGridView control named dataGridViewl, and then public Form10
create another SqlDataAdapter named adp1 for the second DataGridView control named
dataGridView2. You can notice that a single DataSet is used to fill different data in he two InitializeComponent(0:
DataGridView controls. When you run the application, you can see the
output, as shown
Figure 1247: Eventargse
private void FormLoad(object sender
dataGridviewl.Datasource GetrableO.Defaulcview

Dublic Datarable setnable0


Source=GARIMA-PC;Initial
"Data Security=True"
connectionstringIntegrated
Catalog=Northwind;
String
537
536
Data Access with ADO.NET
Chapter 12 new
DataTable("customers")
(connectionstrina
DataTable
customers
connection = new Sq1connection in
(sqconnection
using SoAbyyN y
sqlCommand selectAt]customersconnectjon.createCommand ();
= "select
* from (customers]"; CarparyNe td
selectAl1customers.commandText S May
URACD

connection.open0
CUstomers.Load(selectA1customers.ExecuteReader
Owo
AFFE
Pb
C C o m m a n d e e h a v i o r . c l o s e c o n n e c t i o n ) ) ;

ALED

AS
return customers;
ULA S o
MAGAA

buttonlclick (object sender, EventArgs e) Flgure 12.49: Showing the Sorted Data
private void
On clicking Only
in
new
Dataview(GetTabie0); Mexico Button,
you can tilter the data and displays only those records whose
City field
Dataview
dv.sort
dv"city ASC";
contains Mexico. The output after clhcking the Only in Mexico button is shown in Figure 12.50:
dataGridview1.bataSource = dv;
Formd

private void button2_click(object sender, EventArgs e) r

Dataview dv = new Datavi ew(GetTable0) ANTON

CENTC
dv.RoWFi1ter ="Country "Mexico
dataGridviewl.DatasSource dv;
PERC
TORTU Toga Rean a a g PaOne

NOTE Figure 12.50: Showng the FilRered Data


You need to modity the value of the ConnectionString property according to your computer configuration. You need to
add the System.Data. SqiClient namespace in the Form 1.cs file.
Using DataReader to Work with Databases
instead of DataAdapter. You
As per Listing 1210, the datais retrieved in the DataGridView control when you run the application. You retrieve the data in Windows application by using DataReader
can
Read () method of
The initial output of the application is shown in Figure 12.48: can usethe ExecuteReader to retrieve the rows from a data source. The
are different DataReaders for different
DataReader is used to obtaina row from the data source. There
Forml
data sources. For example, 0le Db Data Reader provides a way
of reading forward only stream of data
stream
from OLE DB data The aReader provides a way of reading forward only
SqlDat
rows provider.
Son by Cy nyn Meuco
of data rows from an SQL Server data source. Let's create an application, named UsingDataRe ader, in
DataReader. For this, you first need to add
CutonerlD ompanyNeTe rlazeme
Cortace Ad
which you can retrieve data from a data source using controls to Forml,
controls to Forml. After adding the
5utton, Label, TextBox, and
ALFN reds iekse Mana Andes ListBox
Sales Represert 0br
and the Text property of the
ANATR control to Enter Text to Find,
Cnange the Text property of the
Ana Tnlo Empa Ana Trnilo Label
Owner AV
ANTON Arlano Noreno
tono Moreno OWmer Button contr to Fin d.
AROUT Around the Hom Thomas Hardy
Click event of the Button control:
Sales Represert120 the
highlighted code, shown in Listing 12.11,
on
BERGS Now, add the
Berginds snabbOvnstna Bergknd Order Adminestrator Ber
Button Control
BLAUS
BLONP
Blauer See Delik Harma Moos
Sales Represert.. Fon Listing 1211: Showing Code for the Click Event of the
Bondesddal père Frédénque Cteaux Marketing Manager 24 using System;
30LID Báldo Comdes o... Martn Sommer Owner
using System.collections.Generic;
Using System.ComponentModel;
using System.Data;
Figure 12.48: Showing the Initial Output of the
On Application Using syStem.bataSalclfert
clicking
the Sort by City button
you can sort the data of the 9using system.Drawingi
City field in ascending order. The output on DataGridView control the
clicking the Sort by City button is shown in
on
basis o using system. Linq;
Figure 12.4 using System. Text;
using System. Threading. Tasks;
using System.windows.Forms;
namespace usingoatareader 539
538
Chapter 12 Data Access with ADO.NET
Form
Foml
class Forml:
publicpartial
bter led to Fnd
public Form10 F

Initializecomponent():

Andrew Fulr

buttonlclick(object sender, EventArgs e)


private void

sq1Datareader rdr null


5q1Connection con E null;
SqlCommand cmd nuli;
try Figure 12.51: Showing the Output of the UsingData Reader Application
summarize the
main points of this chapter.
string Connectionsrtring "Data Source=GARIMA-PC;Inítial Let's
Catalog=northwind;Integrated security=True
con new Sqlconnection(Connectionsrtring);
SummaryY
con.openO:
Tn this chapter, you
have learned about sQL, and ADO.NET. In addition, you have learned about
databases,
string commandText= FirstName,
"SELECT LastName + FROM
Employees" several SQL statements and clauses to perform various operations on database. Next, you have leamed about
WHERE (LastName LIKE @Find)"; arious aspects of ADO.NET including its architecture and ADO.NET Entity Framework. You have also learned
cmd=new Sqlcommand (Commandtext)
connection strings, connection to a database, and a command object as well as how to work with
CMd.connection con; how to create
DataAdapters and DataReader.
cmd Parame ters .Add (new
sqlParameter("@Find",systen.Data.sqlobType.NVarchar, 20,"LastName") In the next chapter, you learn about how to work with LINQ.
Cmd.Parameters["@Find"].value = textBoxl.1ext

rdrcmd.ExecuteReader): Quick Revise


listBoxl.items.clear O: used to fill dataset?
while (rdr.Read)) Which method of the data adapter is a
Q1.
1isteox1.Items.Add(rdr["FirstName"] TostringO +""
Ans. Fill () method
rdr["LastName"].Tostring0): What does Execut eNonQuery () method
do?
Q2. data
executes commands that do not return
rows.

Ans. The ExecuteNonQuery () method


catch (EXception ex)1 to bind a DataGridView control?
used
Q3. Which properties are
Messagesox.Show(ex.Message); DataSource and DataMember properties
Ans.
finally the various components of
DataSet?
if.Crdr 1= nul1) Q4 What are

of dataset are listed as follows:


The various components
rdr.closeO; Ans
if (con.State ConnectionStatë.open) DataTable
con.closeO ODataView
a DataColumn
a DataRow
ODataRela tion table?
NOTE Q5. Which statement is used to delete a

You need to modiy the value of the


add the
ConnectionString property according
System.Data. SqlClient namespace in the Form 1.cs file.
to your computer configuration. You need to Ans The DROPstatement.
DISTINCT clause.
Q6. Explain the use of the table without duplicating
them.
the data from a

Run the application by pressing the F5 Ans. The DISTINCT clause is used to retrieve
key. As you enter the starting letter of the employee's last DataSet? Differentiate
them.
with the % wildcard character, and click the Find
button, the first name and the last name of the
name Q7. What are the different types of a
The Typed dataset con tains a schema whereas
the

Typed and Untyped.


employee is displayed in the ListBox control. You can find the with Fs in the
output TextBox, as shown
Ans.
A Dataset is of two types:
schema.
in Figure 1251: contain a
Untyped dataset does not
allows to access

Q8. What is theuse of a DataReader? A DataReader


data source.
read data from a record loaded
in the memory
Ans. is used to sequentially single
A DataRe adera
a
time having
at a given
row of data
nrormation on single
the result set. 541
regardless of the size of
540
Ann

Q0 What a the funtlonally of dala ln ADONIT7


pruvlder
Ann
wovN Vsulta A dala unvlor in n nl rulalul vmnpmonta thal work ugtbwr ui pnrvulw hata im
ft lon mannwr

You might also like