Anda di halaman 1dari 29

ADO.

NET Architecture
ADO.NET is a data access technology Irom MicrosoIt .Net Framework , which provides
communication between relational and non-relational systems through a common set oI
components . ADO.NET consist oI a set oI Objects that expose data access services to the
.NET environment. ADO.NET is built Ior disconnected architecture , so it enables truly
disconnected Data Access and Data Manipulation through its Dataset Object, which is
completely independent Irom the Data Source.

The two key components oI ADO.NET are Data Providers and DataSet . The .Net
Framework includes mainly three Data Providers Ior ADO.NET. They are the MicrosoIt SQL
Server Data Provider, OLEDB Data Provider and ODBC Data Provider. SQL Server uses the
SqlConnection object , OLEDB uses the OleDbConnection Object and ODBC uses
OdbcConnection Object respectively.

The Iour Objects Irom the .Net Framework provide the Iunctionality oI Data Providers in the
ADO.NET. They are Connection Object, Command Object , DataReader Object and
DataAdapter Object. The Connection Object provides physical connection to the Data
Source. The Command Object uses to perIorm SQL statement or stored procedure to be
executed at the Data Source. The DataReader Object is a stream-based , Iorward-only, read-
only retrieval oI query results Irom the Data Source, which do not update the data. Finally the
DataAdapter Object , which populate a Dataset Object with results Irom a Data Source .

DataSet provides a disconnected representation oI result sets Irom the Data Source, and it is
completely independent Irom the Data Source. DataSet provides much greater Ilexibility
when dealing with related Result Sets. DataSet consists oI a collection oI DataTable objects
that you can relate to each other with DataRelation objects. The DataTable contains a
collection oI DataRow and DataCoulumn Object which contains Data. The DataAdapter
Object provides a bridge between the DataSet and the Data Source.


ADO.NET ConnectionString
Connection String is a normal String representation which contains Database connection
inIormation to establish the connection between Datbase and the Application. The
Connection String includes parameters such as the name oI the driver, Server name and
Database name , as well as security inIormation such as user name and password. Data
providers use a connection string containing a collection oI parameters to establish the
connection with the database.
The .NET Framework provides mainly three data providers: MicrosoIt SQL Server, OLEDB
and ODBC. Here you can see how to make connection string to these ADO.NET Data
Providers.
Microsoft SQL Server Connection String
connetionString "Data Source ServerAame; Initial Catalog Databasename; User ID
UserAame; PasswordPassword"
OLEDB Data Provider Connection String
connetionString "Provider Microsoft.1et.OLEDB.4.; Data Source
yourdatabasename.mdb;"
ODBC Connection String
connetionString "Driver {Microsoft Access Driver (.mdb)]; DBQ
yourdatabasename.mdb;"
Note : You have to provide the necessary inIormations to the Connection String attributes.
In the Iollowing section you can see how to these ADO.NET Data Providers establish
connection to the Databse in detail.
SQL Server Connection
OLEDB Connection
ODBC Connection

Advantages of ADO.Net over ADO
ADO stands Ior ActiveX Data Objects and it relies on COM whereas ADO.NET relies on
managed providers deIined by the .NET CLR (Common Language Runtime). ADO.NET
provides consistent access to data sources such as SQL Server, as well as data sources
exposed through OLE DB and XML. While there are similarities between ADO and
ADO.NET, the way they operate and their Ioundations are quite diIIerent. The Iollowing are
some Advantages oI ADO.Net over ADO in basic level.
A major diIIerence in creating connections with ADO and ADO.NET is that ADO Iits all
connections to all types oI data sources into a single Connection object. ADO.NET can have
separate Objects that represent connections to diIIerent data sources. In ADO.NET you can
create multiple data provider namespaces to connect speciIically with a particular data
source, making access Iaster and more eIIicient and allowing each namespace to exploit the
Ieatures oI its targeted data provider.
Dim connection As SqlConnection
connection = New SqlConnection("connetionString")
Dim connection As OleDbConnection
connection = New OleDbConnection("connetionString")
ADO allows you to create client side cursors only whereas ADO.NET gives you the choice oI
either using client side or server side cursors.
ADO.NET introduces a new way oI getting a single value Irom a query's results when you
expect only one row and one column to return. The ADO.NET command object has an
ExecuteScalar method which returns the Iirst row and column's value Irom its associated
query.
ADO.Net dataset represents in memory representation oI a database. ADO recordsets is
merely a set oI rows retrieved Irom a data source.
ADO recordsets can hold data Irom one data source at a time. ADO.Net datasets can hold
data Irom various sources and integrate the data and write it back to one or several data
sources.
The ADO.NET Framework supports two models oI Data Access Architecture, Connection
Oriented Data Access Architecture and Disconnected Data Access Architecture.
In the case oI Data Communication , ADO objects communicate in binary mode while
ADO.NET uses XML Ior passing the data.

ADO.NET Data Providers
The .Net Framework includes mainly three Data Providers Ior ADO.NET. They are the
MicrosoIt SQL Server Data Provider , OLEDB Data Provider and ODBC Data provider. You
can see Irom the Iollowing links how these Data Providers making connection to the
speciIied data Sources.
SQL Server Connection
OLEDB Connection
ODBC Connection

The Iour Objects Irom the .Net Framework provide the Iunctionality oI Data Providers in
ADO.NET. They are Connection Object, Command Object , DataReader Object and
DataAdapter Object. The Iollowing link shows in details about these Objects.
Connection
Command
DataReader
DataAdapter

ADO.NET Command
The Command Object in ADO.NET executes SQL statements and Stored Procedures against
the data source speciIied in the Connection Object. The Command Object required an
instance oI a Connection Object Ior executing the SQL statements. That is, Ior retrieving data
or execute an SQL statement against a Data Source , you have to create a Connection Object
and open a connection to the Data Source, and assign the open connection to the connection
property oI the Command Object. When the Command Object return result set , a Data
Reader is used to retrieve the result set.

The Command Object has a property called CommandText, which contains a String value
that represents the command that will be executed in the Data Source. When the
CommandType property is set to StoredProcedure, the CommandText property should be set
to the name oI the stored procedure.
Click the Iollowing links to see some important built in methods uses in the Command Object
to execute the SQL statements.
ExecuteNonQuery
ExecuteReader
ExecuteScalar
ADO.NET ExecuteNonQuery in SqlCommand Object
ExecuteNonQuery() is one oI the most Irequently used method in SqlCommand Object and is
used Ior executing statements that do not return result set. ExecuteNonQuery() perIorms Data
DeIinition tasks as well as Data Manipulation tasks also. The Data DeIinition tasks like
creating Stored Procedures and Views perIorm by ExecuteNonQuery() . Also Data
Manipulation tasks like Insert , Update and Delete perIorm by ExecuteNonQuery().
ADO.NET ExecuteReader in SqlCommand Object
ExecuteReader() in SqlCommand Object send the SQL statements to Connection Object and
populate a SqlDataReader Object based on the SQL statement. When the ExecuteReader
method in SqlCommand Object execute , it instantiate a SqlClient.SqlDataReader Object.
The SqlDataReader Object is a stream-based , Iorward-only, read-only retrieval oI query
results Irom the Data Source, which do not update the data. The SqlDataReader cannot be
created directly Irom code, they created only by calling the ExecuteReader method oI a
Command Object.
ADO.NET ExecuteScalar in SqlCommand Object
ExecuteScalar() in SqlCommand Object is used Ior get a single value Irom Database aIter its
execution. It executes SQL statements or Stored Procedure and returned a scalar value on
Iirst column oI Iirst row in the Result Set. II the Result Set contains more than one columns
or rows , it takes only the Iirst column oI Iirst row, all other values will ignore. II the Result
Set is empty it will return a Null reIerence.
It is very useIul to use with aggregate Iunctions like Count(*) or Sum() etc. When compare to
ExecuteReader() , ExecuteScalar() uses Iewer System resources.
What is DataAdapter
DataAdapter is a part oI the ADO.NET Data Provider. DataAdapter provides the
communication between the Dataset and the Datasource. We can use the DataAdapter in
combination with the DataSet Object. That is these two objects combine to enable both data
access and data manipulation capabilities.

The DataAdapter can perIorm Select , Insert , Update and Delete SQL operations in the Data
Source. The Insert , Update and Delete SQL operations , we are using the continuation oI the
Select command perIorm by the DataAdapter. That is the DataAdapter uses the Select
statements to Iill a DataSet and use the other three SQL commands (Insert, Update, delete) to
transmit changes back to the Database. From the Iollowing links describe how to use
SqlDataAdapter and OleDbDataAdapter in detail.
SqlDataAdapter
OleDbDataAdapter

ADO.NET Objects
A0D.NET Includes many objects you can use to work wIth data. ThIs sectIon
Introduces some of the prImary objects you wIll use. Dver the course of thIs
tutorIal, you'll be exposed to many more A0D.NET objects from the perspectIve of
how they are used In a partIcular lesson. The objects below are the ones you must
know. LearnIng about them wIll gIve you an Idea of the types of thIngs you can do
wIth data when usIng A0D.NET.
The SqIConnectIon Dbject
To Interact wIth a database, you must have a connectIon to It. The connectIon
helps IdentIfy the database server, the database name, user name, password, and
other parameters that are requIred for connectIng to the data base. A connectIon
object Is used by command objects so they wIll know whIch database to execute
the command on.
The SqICommand Dbject
The process of InteractIng wIth a database means that you must specIfy the actIons
you want to occur. ThIs Is done wIth a command object. You use a command
object to send SQL statements to the database. A command object uses a
connectIon object to fIgure out whIch database to communIcate wIth. You can use
a command object alone, to execute a command dIrectly, or assIgn a reference to
a command object to an Sql0ataAdapter, whIch holds a set of commands that work
on a group of data as descrIbed below.
The SqI0ataPeader Dbject
|any data operatIons requIre that you only get a stream of data for readIng. The
data reader object allows you to obtaIn the results of a SELECT statement from a
command object. For performance reasons, the data returned from a data reader
Is a fast forwardonly stream of data. ThIs means that you can only pull the data
from the stream In a sequentIal manner. ThIs Is good for speed, but If you need to
manIpulate data, then a 0ataSet Is a better object to work wIth.
The 0ataSet Dbject
0ataSet objects are Inmemory representatIons of data. They contaIn multIple
0atatable objects, whIch contaIn columns and rows, just lIke normal database
tables. You can even defIne relatIons between tables to create parentchIld
relatIonshIps. The 0ataSet Is specIfIcally desIgned to help manage data In memory
and to support dIsconnected operatIons on data, when such a scenarIo make
sense. The 0ataSet Is an object that Is used by all of the 0ata ProvIders, whIch Is
why It does not have a 0ata ProvIder specIfIc prefIx.
The SqI0ataAdapter Dbject
SometImes the data you work wIth Is prImarIly readonly and you rarely need to
make changes to the underlyIng data source. Some sItuatIons also call for cachIng
data In memory to mInImIze the number of database calls for data that does not
change. The data adapter makes It easy for you to accomplIsh these thIngs by
helpIng to manage data In a dIsconnected mode. The data adapter fIlls a 0ataSet
object when readIng the data and wrItes In a sIngle batch when persIstIng changes
back to the database. A data adapter contaIns a reference to the connectIon
object and opens and closes the connectIon automatIcally when readIng from or
wrItIng to the database. AddItIonally, the data adapter contaIns command object
references for SELECT, NSEFT, UP0ATE, and 0ELETE operatIons on the data. You
wIll have a data adapter defIned for each table In a 0ataSet and It wIll take care
of all communIcatIon wIth the database for you. All you need to do Is tell the data
adapter when to load from or wrIte to the database.
Summary
A0D.NET Is the .NET technology for InteractIng wIth data sources. You have
several 0ata ProvIders, whIch allow communIcatIon wIth dIfferent data sources,
dependIng on the protocols they use or what the database Is. Fegardless, of whIch
0ata ProvIder used, you'll use a sImIlar set of objects to Interact wIth a data
source. The SqlConnectIon object lets you manage a connectIon to a data source.
SqlCommand objects allow you to talk to a data source and send commands to It.
To have fast forwardonly read access to data, use the Sql0ataFeader. f you want
to work wIth dIsconnected data, use a 0ataSet and Implement readIng and wrItIng
to/from the data source wIth a Sql0ataAdapter.


Wbat is ADU.NET?
ADO.NET is the new database technology oI the .NET (Dot Net) platIorm, and it builds on
Microsoft ActiveX Data Objects (ADO).
ADO is a language-neutral object model that is the keystone oI MicrosoIt's Universal Data
Access strategy.
ADO.NET is an integral part oI the .NET Compact Framework, providing access to
relational data, XML documents, and application data. ADO.NET supports a variety oI
development needs. You can create database-client applications and middle-tier business
objects used by applications, tools, languages or Internet browsers.
ADO.NET deIines DataSet and DataTable objects which are optimized Ior moving
disconnected sets oI data across intranets and Internets, including through Iirewalls. It also
includes the traditional Connection and Command objects, as well as an object called a
DataReader that resembles a Iorward-only, read-only ADO recordset. II you create a new
application, your application requires some Iorm oI data access most oI the time.
ADO.NET provides data access services in the MicrosoIt .NET platIorm.
You can use ADO.NET to access data by using the new .NET Framework data providers
which are:
O uaLa rovlder for SCL Server (System.Data.SqlClient)
O uaLa rovlder for CLLu8 (System.Data.JleDb)
O uaLa rovlder for Cu8C (System.Data.Jdbc)
O uaLa rovlder for Cracle (System.Data.JracleClient)
ADO.NET is a set oI classes that expose data access services to the .NET developer. The
ADO.NET classes are Iound in System.Data.dll and are integrated with the XML classes in
System.Xml.dll.
There are two central components oI ADO.NET classes: the DataSet, and the .NET
Framework Data Provider.
Data Provider is a set oI components including:
O Lhe Connect|on ob[ect (SqlConnection JleDbConnection JdbcConnection
JracleConnection)
O Lhe Command ob[ect (SqlCommand JleDbCommand JdbcCommand JracleCommand)
O Lhe atakeader ob[ect (SqlDataReader JleDbDataReader JdbcDataReader
JracleDataReader)
O and Lhe ataAdapter ob[ect (SqlDataAdapter JleDbDataAdapter
JdbcDataAdapter JracleDataAdapter)
DataSet object represents a disconnected cache oI data which is made up oI DataTables and
DataRelations that represent the result oI the command.
Tbe ADU.NET Ub|ect Model

top
. Connection to an ADU.NET database
BeIore working with a database, you have to add (here) the JleDb .NET Data Provider
namespace, by placing the Iollowing at the start oI your code module:
Collapse | Copy Code
:sing System.Data.JleDb;
Similarly Ior the SqlClient .NET Data Provider namespace:
Collapse | Copy Code
:sing System.Data.SqlClient;
The :sing statement should be positioned Iirst in your code.
Now, we have to declare a connection string pointing to a MS Access database
"!ersonDatabase.mdb".
Collapse | Copy Code
p:blic string
conString=@"Provider=Microsoft.Jet.JLEDB.4.0;" +
@" DataSo:rce=..\\..\\PersonDatabase.mdb";
The database should be in the speciIied path, otherwise you should change the path
accordingly.
The next step is to create an JleDbConnection object. We pass then the connection string to
this JleDbConnection object. You can code now to create a new ADO.NET Connection
object in order to connect to an OLE DB provider database.
Collapse | Copy Code
JleDbConnection con = new JleDbConnection(conString);
You can also explicitly reIerence declared objects iI you dont mind typing a lot.
Collapse | Copy Code
System.Data.JleDb.JleDbConnection con =
new System.Data.JleDb.JleDbConnection(conString);
Here is the code snippet Ior connection to a database:
Collapse | Copy Code
:sing declaration for JLE DB

:sing System.Data.OleDb;
specify the ConnectionString property

p:blic string conString=
@"Provider=Microsoft.Jet.JLEDB.4.0;Data
So:rce=..\\..\\PersonDatabase.mdb";
nitializes a new instance of the JleDbConnection

OleDbConnection con = new OleDbConnection(conString);
open the database connection with the property settings

specified by the ConnectionString "conString"

con.Jpen();
In many earlier applications, the tendency was to open a connection when you start the
application and not close the connection until the application terminates. It is an expensive
and time-consuming operation to open and close a database connection. Most databases have
a limit on the number oI concurrent connections that they allow.
For example: each connection consumes a certain amount oI resources on the database server
and these resources are not inIinite. Most modern OLE DB providers (including SQL Server
provider) implement .onne.tion pooling. II you create database connections, they are held in
a pool. When you want a connection Ior an application, the OLE DB provider extracts the
next available connection Irom the pool. When your application closes the connection, it
returns to the pool and makes itselI available Ior the next application that wants a connection.
This means that opening and closing a database connection is no longer an expensive
operation. II you close a connection, it does not mean you disconnect Irom the database. It
just returns the connection to the pool. II you open a connection, it means it's simply a matter
oI obtaining an already open connection Irom the pool. It's recommended in many
ADO.NET books not to keep the connections longer than you need to. ThereIore, you
should:
O Cpen a connecLlon when you need lL and
O Close lL as soon as you have flnlshed wlLh lL
For example: here is another way to get a connection to a database:
Collapse | Copy Code
set:p the global SqlConnection object and constr in yo:r class

private SqlConnection con = n:ll;
private string constr ="ntegrated Sec:rity=SSP;" +
"nitial Catalog=Northwind;" +
"Data So:rce=SJNY\\MYSQLSERVER;";

private void fnGetConnection()
,
try
,
set:p the database connection

con = new SqlConnection(constr);
con.Jpen();
,catch (Exception ex) ,
MessageBox.Show("Error in connection : "+ex.Message);
,finally ,
dispose of open objects

if (con != n:ll)
con.Close();
, finally

,
For example: you want to open the connection, Iill the DataSet, and close the connection. II
the connection Iails, you want to get the error message.
Collapse | Copy Code
try
,
con.Jpen();
dadapter.Fill(dataset1);
con.Close();
, catch (Exception ex) ,
MessageBox.Show("Error in retrieving data: " + ex.Message);
,
For example: iI you want to save the data you changed, then you just open the connection,
update the data, and close the connection and accept the changes. II it Iails, display an error
message, reject the changes, and close the connection.
Collapse | Copy Code
try
,
DataSet changes = dataset.GetChanges();
con.Jpen();
datapter.Update(changes);
con.Close();
dataset1.AcceptChanges();
,catch (Exception ex) ,
MessageBox.Show("ErrorR: " + ex.Message);
dataset1.RejectChanges();
con.Close();
,
top
. DataSet
The DataSet is similar to an array oI disconnected Recordset objects. It supports
disconnected data access and operations, allowing greater scalability because you no longer
have to be connected to the database all the time. DataSet is a copy oI an extracted data
being downloaded and cached in the client system.
The DataSet object is made up oI two objects:
O DataTableCollection ob[ecL conLalnlng null or mulLlple DataTable ob[ecLs (Columns
8ows ConsLralnLs)
O DataRelationCollection ob[ecL conLalnlng null or mulLlple DataRelation ob[ecLs
whlch esLabllsh a parenL/chlld relaLlon beLween Lwo DataTable ob[ecLs
Collapse | Copy Code
Create a DataSet

DataSet dset = new DataSet();
There are two types oI DataSets:
@ped ataSet
2 Dntped ataSet
. Typed DataSet is derived Irom the base DataSet class and then uses inIormation in an
XML Schema Iile (.xsd Iile) in order to generate a new class. InIormation Irom the schema
(tables, columns, and so on) is generated and compiled into this new DataSet class as a set oI
Iirst-class objects and properties. Typed dataset is easier to read. It's also supported by
IntelliSense in the Visual Studio Code Editor. At compile time, it has type checking so that
there are less errors in assigning values to DataSet members. ThereIore, using Typed
DataSet has many advantages.
Example: the Iollowing code accesses the C:stomerD column in the Iirst row oI the
:stomers table.
Collapse | Copy Code
string str;
str=dset.C:stomers0,.C:stomerD;
Create a typed DataSet without designer - manually
O Call Lhe command prompL (cmJ) aL Lhe locaLlon of Lhe xSu schema flle
O Dse Lhe OO uLlllLy Lo creaLe Lhe class for Lhe Lyped DataSet
Collapse | Copy Code
xsd.exe d l:cs mydataset.xsd n:mynamespace
d : yo: create a DataSet.
l:cs - set the lang:age as C#.
n:mynamespace - the class sho:ld :se the namespace "mynamespace".
The output oI XSD.EXE with these arguments will be a ..s class Iile (mydataset..s).
Use .s..exe to compile the class.
Collapse | Copy Code
csc.exe t:library mydataset.cs r:System.dll r:System.Data.dll
r:System.XML.dll o:t:binmydataset.dll t:library
Compile as a library component (DLL).
O /r speclfles assemblles you need Lo reference
O /ouL saves Lhe complled assembly ln Lhe subdlrecLory of Lhe currenL dlrecLory
. Untyped DataSet is not deIined by a schema, instead, you have to add tables, columns and
other elements to it yourselI, either by setting properties at design time or by adding them at
run time. Typical scenario: iI you don't know in advance what the structure oI your program
is that is interacting with a component that returns a DataSet.
The equivalent code above Ior &ntyped DataSet is:
Collapse | Copy Code
string str;

str=(string)dset.Tables"C:stomers",.Row0,."C:stomerD",;
A DataSet is a container; thereIore, you have to Iill it with data.
ou can populate a DataSet in a variety of ways:
O b us|ng ataAdapter ob[ects and I||| method
For example:
Collapse | Copy Code
string strCon = @"Data So:rce=SJNY\MYSQLSERVER;" +
"nitial Catalog=Northwind;ntegrated Sec:rity=SSP";
string strSql="select from c:stomers";
SqlConnection con=new SqlConnection(strCon);
con.Jpen();

SqlDataAdapter dadapter=new SqlDataAdapter();
dadapter.SelectCommand=new SqlCommand(strSql,con);
DataSet dset=new DataSet();
dadapter.Fill(dset);
con.Close();

this.dataGrid1.DataSo:rce=dset;
O b creat|ng ata@ab|e ataCo|umn and atakow ob[ects programmat|ca||
AIter you create a DataTable and deIine its structure using columns and constraints,
you can add new rows oI data to the table.
For example:
Collapse | Copy Code
DataSet dset;
DataTable dtbl;
DataRow drow;
create a new row

drow=dtbl.NewRow();
manip:late the newly added row :sing an index or the col:mn name

drow"LastName",="Altindag";
drow1,="Altindag";
After data is inserted into the new row, the Add method is :sed

to add the row to the DataRowCollection

dtbl.Rows.Add(drow);
Yo: can also call the Add method to add a new row by passing in an

array of val:es, typed as Object

dtbl.Rows.Add(new object, ,1, "Altindag",);
O kead an kML document or stream |nto the ataSet
The Iollowing code creates a SqlConnection object that opens a connection to the
!:bs database, creates a SQL query to get the data oI the A:thors table as XML, and
it creates a new SqlCommand object. AIter creating a new DataSet, it uses the
Exec:teXmlReader method to pass an XmlReader object to the DataSet's ReadXml
method, which allows the DataSet to populate itselI Irom the XmlReader. Finally, the
code sets the Doc:mentContent property to the result oI the GetXml method oI the
DataSet. XML uses the XSL TransIormation document a:thors.xsl (included in the
project) to Iormat the XML content displayed by the XML control.
For example:
Collapse | Copy Code
protected System.Web.U.WebControls.Xml XmlDisplay;

string strCon = @"Data So:rce=SJNY\MYSQLSERVER;" +
"nitial Catalog=p:bs;ntegrated Sec:rity=SSP";
SqlConnection con=new SqlConnection(strCon);

con.Jpen();
try
,
string strSql="select from FRJM a:thors FJR XML AUTJ, XMLDATA";
SqlCommand cmd=new SqlCommand(strSql, con);
DataSet dset=new DataSet();
dset.ReadXml(cmd.Exec:teXmlReader(),XmlReadMode.Fragment);
XmlDisplay.Doc:mentContent = dset.GetXml();
,finally ,
con.Close();
,
O Merge (cop% the contents of another ataSet w|th the Merge method
You can merge two DataSet objects that have largely similar schemas. You can use a
merge typically on a client application to incorporate the latest changes Irom a data
source into an existing DataSet. This allows the client application to have a reIreshed
DataSet with the latest data Irom the data source.
For example:
Collapse | Copy Code
dataset1.Merge(dataset2);
top
. DataAdapter
DataAdapter object is like a bridge that links the database and a Connection object with the
ADO.NET-managed DataSet object through its SELECT and action query Commands. It
speciIies what data to move into and out oI the DataSet. OIten, this takes the Iorm oI
reIerences to SQL statements or stored procedures that are invoked to read or write to a
database.
The DataAdapter provides Iour properties that allow us to control how updates are made to
the server:
O SelectCommand
O UpdateCommand
O nsertCommand
O DeleteCommand
The Iour properties are set to Command objects that are used when data is manipulated.
The DataAdapter includes three main methods:
O Fill (populaLes a DataSet wlLh daLa)
O FillSchema (querles Lhe daLabase for schema lnformaLlon LhaL ls necessary Lo updaLe)
O Update (Lo change Lhe daLabase DataAdapter calls Lhe DeleteCommand Lhe
nsertCommand and Lhe UpdateCommand properLles)
For example:
When we call the DataAdapter's Fill method to retrieve data Irom a data source and pour it
into a DataSet, the Command object in the SelectCommand property is used. The
DataAdapter is the gatekeeper that sits between our DataSet and the data source.
Collapse | Copy Code
Create an instance of a JleDbDataAdapter

by passing JleDbConnection object and select.. q:ery

JleDbDataAdapter dAdapter = new
JleDbDataAdapter ("select from PersonTable", con );
fill the DataSet with records from the table "PersonTable"

dAdapter.Fill(dSet,"PersonTable");
Here is the method used in this project to get a data connection, DataSet and DataAdapter.
You can Iind this method in the Iile "DataA..essTierlass..s".
Collapse | Copy Code
p:blic bool fnGetDataConnection()
,
try ,
con =new JleDbConnection(conString);
dAdapter=new JleDbDataAdapter("select from PersonTable", con);
dSet=new DataSet();
refreshes rows in the DataSet

dAdapter.Fill(dSet,"PersonTable");
,catch(Exception ex) ,
MessageBox.Show("Error : "+ex.Message);
connectection failed

ret:rn false;
,try-catch

connection ok!

ret:rn tr:e;
,
top
. Display data in a DataCrid J data relationsbip between two tables
The Windows Forms DataGrid control displays data in a series oI rows and columns. The
Windows Forms DataGrid control provides a user interIace to ADO.NET DataSets. It
displays tabular data and allows Ior updates to the data source. When you set a DataGrid
control to a valid data source, the control will be automatically populated, creating columns
and rows based on the shape oI the data.
You can use the DataGrid control Ior displaying either a single table or the hierarchical
relationships between a set oI tables. II you want to work with the DataGrid control,
DataGrid should be bound to a data source by using:
O Lhe DataSo:rce and DataMember properLles aL deslgn Llme or
O Lhe SetDataBinding meLhod aL run Llme
Here is the binding to the DataGrid control with DataSet I used in this project:
Collapse | Copy Code
this.dataGrid1 DataSo:rce = datc.dSet.Tables"PersonTable",;
You can only show one table in the DataGrid at a time.
II you deIine a parent-child relationship between tables, you can navigate between the
related tables to select the table you want to display in the DataGrid control.
For example:
Collapse | Copy Code
dset.Relations.Add("C:stomerJrders",
dset.Tables"c:stomers",.Col:mns"C:stomerD",,
dset.Tables"orders",.Col:mns"C:stomerD",);
now here yo: can :se one of the following

this.dataGrid1.DataSo:rce=dset.Tables"c:stomers",;
OR
Collapse | Copy Code
this.dataGrid1.SetDataBinding(dset,"c:stomers");
O c:stomers arenL Lable
O orders Chlld Lable
O C:stomerD ln Je ls a forelgn key referrlng Lo C:stomerD prlmary key ln me
Lable
Here is a typical example oI how to use the parent-child relationship between the tables
"Customers" and "Orders" on a DataGrid control.
The DataRelation in this example allows you to navigate Irom one DataTable
("Customers") to another DataTable ("Orders") within a DataSet. The DataSet class can
contain null or many DataTable objects. "Customers" and "Orders" DataTables contain a
column named "C:stD", which is a link between these two DataTable objects.
To run and test this example, create a new project, drag/drop a B:tton (here: b:tton1) and a
DataGrid (here: dataGrid1) on the Form and copy the Iollowing code snippets
(fnGetConnectionString(), b:tton1_Click) and you additionally need SQL Server 2000
running or MS-Access.
Collapse | Copy Code
p:blic string fnGetConnectionString()
,
it gives back the connection string :

change for yo: the Data So:rce=.... accordingly

for MS-Access

ret:rn "Provider=Microsoft.Jet.JLEDB.4.0;

Data So:rce=..\\..\\Northwind.mdb";

for SQLSERVER2000

ret:rn "data so:rce=SJNY\\MYSQLSERVER;initial" +
" catalog=Northwind;integrated sec:rity=SSP;";
,
Collapse | Copy Code
private void b:tton1_Click(object sender, System.EventArgs e)
,
for SQLServer2000

DataSet dset=new DataSet();
string strC:stomers="select from c:stomers";
string strJrders="select from orders";

SqlConnection sqlcon=new SqlConnection(fnGetConnectionString());

SqlDataAdapter dadapter=new SqlDataAdapter(strC:stomers,sqlcon);
dadapter.Fill(dset,"C:stomers");

dadapter=new SqlDataAdapter(strJrders,sqlcon);
dadapter.Fill(dset,"Jrders");
Add the relation to the DataSet.

dset.Relations.Add("C:stomer Jrders",
dset.Tables"C:stomers",.Col:mns"C:stomerD",,
dset.Tables"Jrders",.Col:mns"C:stomerD",);

Display data in the DataGrid

both works fine

this.dataGrid1.DataSo:rce=dset.Tables"C:stomers",;
this.dataGrid1.SetDataBinding(ds,"C:stomers");


for MS-Access



create a DataSet object which will contain the following 2 DataTables
DataSet dset=new DataSet();

string strC:stomers="select from c:stomers";
string strJrders="select from orders";

JleDbConnection con=new JleDbConnection(fnGetConnection());

JleDbDataAdapter dadapter=new JleDbDataAdapter(strC:stomers,con);
fill the DataSet with the records from the C:stomers table
dadapter.Fill(dset,"C:stomers");

dadapter=new JleDbDataAdapter(strJrders,con);
fill the DataSet with the records from the Jrders table
dadapter.Fill(dset,"Jrders");

establish the relation between the 2 DataTable objects
dset.Relations.Add("C:stomer Jrders",
dset.Tables"C:stomers",.Col:mns"C:stomerD",,
dset.Tables"Jrders",.Col:mns"C:stomerD",);

both works fine
this.dataGrid1.DataSo:rce=dset.Tables"C:stomers",; show the data in
DataGrid
this.dataGrid1.SetDataBinding(ds,"C:stomers");


,
Now iI you update the data in the bound DataSet through any mechanism, the DataGrid
control reIlects the changes. You can update the data in the DataSet through the DataGrid
control, iI the DataGrid and its table styles and column styles have the ReadJnly property set
to false. There are Iour most typical valid data sources Ior the DataGrid:
O DataTable class
O DataView class
O DataSet class
O DataViewManager class
The Iirst time this application was published, I got e-mails Irom users asking me how to get
the contents oI a DataGrid cell you clicked, or how to get the DataGrid row contents you
clicked. So now, I've one method to do that and didn't want to withhold it Irom you.
Collapse | Copy Code
yo: click in the cell or the rows

of the DataGrid and get the content of it


private void dataGrid1_C:rrentCellChanged(object sender, System.EventArgs
e)
,
be warned: if yo: click the last cell on the Datagrid yo: get
an :nhandled exception of type 'System.Arg:mentJ:tJfRangeException.
beca:se there is no f:rther col:mns after the last col:mn(Co:ntry)
to avoid this tried a different way: in a try-catch get the right
cell content. if the last col:mn cell clicked, display the exception
and the cell content one before. B:t yo: can comment
the MessageBox.Show line if not wished

get the row n:mber on the DataGrid

int iRownr=this.dataGrid1.C:rrentCell.RowN:mber;
get the col:mn n:mber on the DataGrid

int iColnr=this.dataGrid1.C:rrentCell.Col:mnN:mber;
get the content of the cell in the clicked cell on the Datagrid

object cellval:e1=this.dataGrid1iRownr, iColnr,;
object cellval:e2=n:ll;
get the next cell content in the same row

try ,
cellval:e2=this.dataGrid1iRownr, iColnr+1,;
display (cellval:e1+cellval:e2) in TextBox "textBox1"

this.textBox1.Text=cellval:e1.ToString()+" "+cellval:e2.ToString();
, catch(Exception ex) ,
the exception occ:rs here beca:se we increment iColnr+1

MessageBox.Show("No f:rther col:mns after the last " +
"col:mn(Co:ntry) -- "+ex.Message,"STJP");
cellval:e2=this.dataGrid1iRownr, iColnr-1,;
display this time (cellval:e2+cellval:e1) in TextBox "textBox1"

this.textBox1.Text=cellval:e2.ToString()+" "+cellval:e1.ToString();
,catch

,
top
. DataBindings for TextBoxes
DataBinding is the ability to bind some elements oI a data source with some graphical
elements oI an application.
The data in Windows Forms is bound by calling DataBindings. Windows Forms allows you
to bind easily to almost any structure that contains data.
Windows Forms Controls support two types oI data binding:
O mple ff 8J
O mplex ff 8J
. Simple Data Binding allows you to display a single data element, such as a column value
Irom a DataSet table, in a control. You can simple-bind any property oI a control to a data
value. Simple Data Binding can be perIormed either at design time using DataBindings
property oI a control or dynamically at run time. This is the type oI binding typical Ior
controls such as a TextBox control or Label control that displays typically only a single
value.
For example:
Collapse | Copy Code
Simple DataBinding for TextBox "textBox1"

textBox1.DataBindings.Add("Text", dataset, "st:dentTable.st:dentD");
The control "textBox1" above is bound to the "st:dentD" column oI a table "st:dentTable"
on the DataSet (dataset) through the BindingContext object.
. Complex data binding is the ability oI a control to bind to more than one data element,
typically more than one record in a database, or to more than one oI any other type oI
bindable data element. DataGrid, ListBox and ErrorProvider controls support complex
data binding.
Typical scenario:
You want to display the names oI products in a list box and then retrieve in a TextBox the
Prod:ctD oI a product which you selected.

For example:
You could add .omplex data binding by using the DataSo:rce and DataMember properties.
Collapse | Copy Code
datagrid1.DataSo:rce = dSet;
Use the DataMember property to specify the DataTable.

datagrid1.DataMember = "PersonTable";
Here is the method used in this project to bind all TextBoxes:
Collapse | Copy Code
private void fnGetDataBindingForTextBoxes()
,
this.textboxFirstname.DataBindings.Add("Text",
datc.dSet.Tables"PersonTable",,"FirstName");
this.textboxLastname.DataBindings.Add("Text",
datc.dSet.Tables"PersonTable",,"LastName");
this.textboxTitle.DataBindings.Add("Text",
datc.dSet.Tables"PersonTable",,"Title");
this.textboxCity.DataBindings.Add("Text",
datc.dSet.Tables"PersonTable",,"City");
this.textboxCo:ntry.DataBindings.Add("Text",
datc.dSet.Tables"PersonTable",,"Co:ntry");
,
top
. Using tbe CurrencyManager

You use the C:rrencyManager object iI you want to keep data-bound controls synchronized
with each other which means showing data Irom the same record. For example: iI you want
to add a TextBox control to a Iorm and bind it to a column oI a table (e.g.,
C:stomers.FirstName) in a DataSet (e.g., dSet), the control is going to communicate with
the BindingContext object Ior this Iorm. In turn, the BindingContext object is going to talk
to the speciIic C:rrencyManager object Ior the data the TextBox control is binding.
Every Windows Form has a BindingContext object keeping track oI all the
C:rrencyManager objects on the Windows Form. C:rrencyManager keeps track oI the
position in the data source. When you bind a data object to a control (i.e., TextBox), a
C:rrencyManager object is automatically assigned. II you bind several controls to the same
data source, they share the same C:rrencyManager.
In a normal case where you are using an ADO.NET database (connecting and closing
database) and displaying the records, e.g., in a DataGrid, you never need the
C:rrencyManager object. B:t iI you want to know the exact position within a data structure
(e.g., table in your database) as I did, you have to use the C:rrencyManager object because
the C:rrencyManager has the Position property Ior this purpose. You can, Ior example,
manipulate the Position property in a Next or Previous or First or Last button which I did in
my program as well.
For example:
II you want to know how many records are in a DataTable, you simply query the
BindingContext object's Co:nt property.
Collapse | Copy Code
this.BindingContextdataset1,"PersonTable",.Co:nt - 1 ;
II you want to get the current position Irom the BindingContext object:
Collapse | Copy Code
this.BindingContextdataset1, "PersonTable",.Position + 1;
AIter data binding, you call and initialize C:rrencyManager Ior your table. Here is the
method I used to initialize the C:rrencyManager Ior the table !ersonTable:
Collapse | Copy Code
p:blic void fnSetC:rrencyManager()
,
c:rrManager = (C:rrencyManager)this.
BindingContext datc.dSet.Tables"PersonTable",, ;
,
top
%. Navigation tbrougb records witb Next, Previous, Last, First buttons
As soon as you get the data populated in the DataGrid, you can navigate through records by
using Next, Previous, Last, First buttons, or by clicking the rows oI the DataGrid, or by
using the arrow keys (Up arrow and Down arrow).
II the DataGrid is currently displaying data, none oI the standard keyboard events are raised
Ior the navigation keys. You can still use Up and Down arrow keys to navigate in the
DataGrid but, because I haven't implemented it, you dont get the record position in the
Stat:sBar.
In order to capture keystrokes on the DataGrid, you have to override the ProcessCmdKey
method that processes a command key. You can Iind this method in section 9.
I also included two new methods in order to highlight the records in the DataGrid by using
Next, Previous, Last or First buttons because you don't normally get the row highlighted in
the DataGrid iI you click such a button. By deIault, iI you click the DataGrid row, the row
will be highlighted with BackColor and ForeColor.

st
method:
Collapse | Copy Code
fnSelectUnselectLastFirstRow(int posi)
II you click First or Last button, the Iirst or last record will be selected and highlighted in the
DataGrid. You invoke Ior that the fnSelectUnselectLastFirstRow() method and pass as
parameter 0 (zero) Ior the Iirst record (fnSelectUnselectLastFirstRow(0);), and
(this.c:rrManager.Co:nt-1) Ior the last record.
Collapse | Copy Code
fnSelectUnselectLastFirstRow(this.c:rrManager.Co:nt-1);
Here is the 1
st
method I used Ior this purpose:
Collapse | Copy Code
private void fnSelectUnselectLastFirstRow (int posi)
,
:nselect the last selectedhighlighted row

this.dataGrid1.UnSelect(this.dataGrid1.C:rrentRowndex);
select the last or first row

this.dataGrid1.Select(posi);
,

nd
method:
Collapse | Copy Code
fnSelectUnselectC:rrentRow(int n:m1, int n:m2)
II you click Next or Previous button, the next or previous record will be selected and
highlighted in the DataGrid. You call Ior that the method
fnSelectUnselectC:rrentRow(); and pass as parameter (1,-1) Ior the next record
(fnSelectUnselectC:rrentRow(1,-1);), or (-1,1) Ior the previous record
(fnSelectUnselectC:rrentRow(-1,1);).
Here is the 2
nd
method used Ior it:
Collapse | Copy Code
private void fnSelectUnselectC:rrentRow(int n:m1, int n:m2)
,
get the c:rrent row index

this.iRowndex=this.dataGrid1.C:rrentRowndex;
increment or decrement the index by (n:m1,b:m2)1,-1 or -1,1 depending
on

Next or Previo:s b:tton beca:se we want to select next or previo:s row

if n:m1 is +1 yo: clicked Next so select next row

if n:m1 -1 yo: clicked Previo:s so select previo:s row

:se in both select and :nselect pl:s(+)

its like in math: e.g.7+(-1)=7-1= 6 or7+(+1)=7+1=8

this.iRowndex=this.iRowndex+n:m1;
select the c:rrent row

this.dataGrid1.Select(this.iRowndex);
increment or decrement the index by -1 or 1

so that we can :nselect the previo:s row

this.iRowndex=this.iRowndex+n:m2;
:nselect the previo:s row

this.dataGrid1.UnSelect(this.iRowndex);
,
Now back to enabling and disabling the buttons:
When you click First button, position will be set to 0 (zero) because the Iirst row starts by
zero.
Collapse | Copy Code
c:rrManager.Position=0;
and
O ulsable I|rst and rev|ous buLLons because Lhere ls no prevlous record ln Lhe daLa source
O Lnable -ext and Last buLLons because Lhere are records forwards
When you click Next button, position in the data is increased by 1 and moved to the next
row.
Collapse | Copy Code
c:rrManager.Position +=1;
and
O Lnable I|rst and rev|ous buLLons as long as Lhere are forward records
O CLherwlse dlsable -ext and Last buLLons whlch means you reached Lhe end of Lhe records
When you click Previous button, position in the data is decreased by -1 and moved to the
previous row.
Collapse | Copy Code
c:rrManager.Position -=1;
and
O Lnable -ext and Last buLLons as long as Lhere are records backwards
O CLherwlse dlsable I|rst and rev|ous buLLons whlch means you reached Lhe beglnnlng of
Lhe records
When you click Last button, position in the data is set to the last record (row).
Collapse | Copy Code
this.c:rrManager.Position=this.c:rrManager.Co:nt-1;
and
O ulsable -ext and Last buLLons because Lhere are no records forwards any more
O CLherwlse enable I|rst and rev|ous buLLons so LhaL you can navlgaLe backwards
To enable and disable the buttons, I use the Iunction/method fnEnableDisableB:ttons with
Iour parameters (two B:ttons, string Ior Stat:sBar, bool Ior tr:eenabling,
falsedisabling).
Collapse | Copy Code
private void fnEnableDisableB:ttons(B:tton bt1, B:tton bt2, string str,
bool b)
,
bt1.Enabled=b;
bt2.Enabled=b;
this.statusBar1.Text=str;
,
top
%. How to trap keystrokes {Up, Down, Esc, NumLock...] in tbe DataCrid
Every time you press the keys Up, Down, NumLock and Esc in the DataGrid, I display text
in the stat:sBarPanel1 and stat:sBarPanel2, but you don't get record numbers displayed
because I thought it would be a bit conIusing and too much coding.
Like many users, I also looked Ior a method to catch the keystrokes in a DataGrid, and
encountered it Iirst in MSDN Library. So I decided to include it in the code so that users can
make use oI it. For most purposes, the standard KeyUp, KeyDown, and KeyPress events can
capture and handle keystrokes. However, not all controls raise the standard KeyUp, KeyDown
events Ior all keystrokes under all conditions. The DataGrid control is one oI them.
II no data was assigned to the grid, the arrow keys (LEFT, RIGHT, UP, and DOWN) raise
only the KeyUp event. II the DataGrid displays data, none oI the standard keyboard events
are raised Ior the navigation keys. The DataGrid is the control Ior which this Ieature is most
Irequently requested. You also can intercept key combinations, including CTRL and ALT.
This technique does not capture the Print Screen key. In order to trap keystrokes in a
Windows Forms control, you can override the ProcessCmdKey method in which I changed
only Stat:sBarPanel Text.
Collapse | Copy Code
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
,
const int WM_KEYDJWN = 0x100;
const int WM_SYSKEYDJWN = 0x104;

if ((msg.Msg == WM_KEYDJWN) || (msg.Msg == WM_SYSKEYDJWN))
,
switch(keyData)
,
case Keys.Down:
this.stat:sBarPanel2.Text="Down";
this.stat:sBarPanel1.Text = "Trapped keystrokes on DataGrid...";
break;

case Keys.Up:
this.stat:sBarPanel2.Text="Up";
this.stat:sBarPanel1.Text ="Trapped keystrokes on DataGrid...";
break;

case Keys.N:mLock:
this.stat:sBarPanel2.Text="N:mLock";
this.stat:sBarPanel1.Text ="Trapped keystrokes on DataGrid...";
break;

case Keys.Escape:
this.stat:sBarPanel2.Text="Escape";
this.stat:sBarPanel1.Text ="Trapped keystrokes on DataGrid...";
invoke the method "fnExitUniversal" from the class "ExitClass"

ExitClass ec=new ExitClass();
ec.fnExitUniversal();
break;


case Keys.Tab:
this.stat:sBarPanel1.Text="Tab Key Capt:red";
break;
case Keys.Control | Keys.M:
this.stat:sBarPanel1.Text="<CTRL+ M Capt:red";
break;
case Keys.Alt | Keys.Z:
this.stat:sBarPanel1.Text="<ALT + Z Capt:red";
break;

, switch

, if


ret:rn base.ProcessCmdKey(ref msg,keyData);
,

Anda mungkin juga menyukai