Professional Documents
Culture Documents
Data Access
with AD0.NET
If you need an Information on:
See page
DataReader 506
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
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
the items
you want to create a new DataSet with
they have ordered from the
customer contact names from
can
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.
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
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.
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
created between matching columns in the parent and child Mapping Entityclent Data Provider
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:
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
pnt Reles
Conneteo pechenaVeons
Create tieoL Serer Database Role
pre webbventEve
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.
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
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
*|
tandiewl Syaea Wndew
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
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
Shionen
uppliery
eonies
Functions
A ur he edom.atn ben t ode DotaSet name
NerthwindDtus
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:
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
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
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
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
cten
Add Connecton
LE y pesou
Advanced.-
Tea Conedaen
ance
PhwindDetrsetEpynkGAD*s
e 8/D1
en
Save e Ceerden Sirig Applkatien Cotgure ten Fie
Dedth
Enne
Yee en
Cekm 17 Pes]
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.
// 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
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")
namespace oLEDBEXcel
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
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
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
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*
Ds pre
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
To w e Ue
CheAnton rG
andrat Be
-1 n
ertheod
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;
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
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
Update () method, the DataAdapter examines the RowState and executes the
property
O Admro
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
You can display multiple tables using a single DataSet by first creating a connection. After that, you public partial class Form2
Form
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
CENTC
dv.RoWFi1ter ="Country "Mexico
dataGridviewl.DatasSource dv;
PERC
TORTU Toga Rean a a g PaOne
Initializecomponent():
Andrew Fulr
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