0% found this document useful (0 votes)
2 views

UNIT 3

Uploaded by

prajapatibhavy10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

UNIT 3

Uploaded by

prajapatibhavy10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

1

Unit – 3 (ADO.Net)

What is C#:
ADO.NET is a module of .Net Framework which is used to
establish connection between application and data sources. Data sources can be
such as SQL Server and XML. ADO.NET consists of classes that can be used to
connect, retrieve, insert and delete data.
ADO is the acronym for ActiveX Data Objects. It allows us to connect
to underlying data or databases. It has classes and methods to retrieve and
manipulate data.
ADO.NET provides a bridge between the front end controls and the
back end database. The ADO.NET objects encapsulate all the data access
operations and the controls interact with these objects to display data, thus hiding
the details of movement of data
The following are a few of the .NET applications that use ADO.NET to connect
to a database, execute commands and retrieve data from the database.
 ASP.NET Web Applications.
 Windows Applications.
 Other Applications.

Creat By : kuldeep padhya


2
Unit – 3 (ADO.Net)

Advantages/Features of Using ADO.NET:


 Maintainability
 Programmability
 Performance
 Scalability
 Interoperability

1. Maintainability: -
ADO.NET is built around the idea of separation of data logic
and user interface. It means that we can create our application in independent
layers. Use N-tier application logic across additional tiers to maintain several user
requests at a time
2. Programmability: -
It is a programming style in which user words are used to
construct statements or evaluate expressions. For example: If we want to select
the “Marks” column from “Kawal” from the “Student” table, the following is the
way to do so. Strongly typed data and easy to write code because Microsoft Visual
Studio .NET framework provides statement completion.
3. Performance: -
It uses disconnected data architecture which is easy to scale as
it reduces the load on the database. Everything is handled on the client-side, so it
improves performance. High performance due to connected mode.
4. Scalability: -
It means meeting the needs of the growing number of clients,
which degrading performance. As it uses disconnected data access, applications
do not retain database lock connections for a longer time. Thus, it accommodates
scalability by encouraging programmers to conserve limited resources and allow
users to access data simultaneously.

Creat By : kuldeep padhya


3
Unit – 3 (ADO.Net)

5. Interoperability: (Different language)


We know that XML documents are text-based formats. So, one
can edit and edit XML documents using standard text-editing tools. ADO.NET
uses XML in all data exchanges and for internal representation of data.

ADO.NET Architecture:
ADO.net architecture, we use a two-tier model to create a bridge between .net
and the backend database, through which applications can access various types
of data using the same methodology and connect to a SQL Server database using
a different set of classes.

Creat By : kuldeep padhya


4
Unit – 3 (ADO.Net)

Types of Architecture:
Ado.net is both connection-oriented as well as disconnection oriented.
Depending upon the functionality of an application, we can make it connection-
oriented or disconnection oriented. We can even use both the modes together in
a single application.
1. Connected Architecture
2. Disconnected Architecture (Connectionless)

1. Connection Mode: -
As the name suggests, connected architecture refers to the fact that the
connection is established for the full time between the database and application.
For e.g. we make a program in C# that is connected with the database for the full
time, so that will be connected architecture.
Connected architecture is forward only and read-only. This means the connected
mode will work only in one particular direction i.e. forward and that too for read-
only purpose. Application issues query then read back results and process them.
For connected architecture, we mainly use the object of the DataReader class.
DataReader is used to retrieve the data from the database and it also ensures that
the connection is maintained for the complete interval of time.
In connected architecture, the application is directly linked with the Database

Creat By : kuldeep padhya


5
Unit – 3 (ADO.Net)

2. Disconnected Mode (Connectionless):


Disconnected architecture refers to the mode of architecture in Ado.net where the
connectivity between the database and application is not maintained for the full
time. Connectivity within this mode is established only to read the data from the
database and finally to update the data within the database.
This means during the processing of the application, we need data so that data is
fetched from the database and kept in temporary tables. After that whenever data
is required, it is fetched from the temporary tables. And finally, when the
operations were completed, the connection was established to update the data
within the database from the temporary tables.
In this mode, application issues query then retrieves and store results for
processing. For this purpose, we use objects of SqlDataAdapter and DataSet
classes.
In disconnected architecture, a Dataset is used for retrieving data from the
database. This way there is no need to establish a connection for the full time
because DataSet acts as temporary storage. All the operations can be performed
on the data using the Dataset and finally modified at the database.

Creat By : kuldeep padhya


6
Unit – 3 (ADO.Net)

ADO.NET Components:
The ADO.NET DataSet is the core component of the disconnected architecture
of ADO.NET. The DataSet is explicitly designed for data access independent of
any data source. As a result it can be used with multiple and differing data
sources, used with XML data, or used to manage data local to the application.
The DataSet contains a collection of one or more DataTable objects made up of
rows and columns of data, as well as primary key, foreign key, constraint, and
relation information about the data in the DataTable objects
1. Connection
2. Command
3. DataReader
4. DataAdapter

1. Connection:
The Connection object provides connectivity to a data source. The Connection
object contains all of the information required to open a connection to the
database
2. Command:
The Command object enables access to database commands to return data,
modify data, run stored procedures, and send or retrieve parameter information.
Command objects provide three methods that are used to execute commands on
the database: “ExecuteNonQuery” Executes commands that have no return values
such as INSERT, UPDATE or DELETE
3. Data Reader:
The DataReader provides a high-performance stream of data from the data
source. The DataReader can provide rows of data directly to application logic
when you do not need to keep the data cached in memory. Because only one row
is in memory at a time, the DataReader provides the lowest overhead in terms of

Creat By : kuldeep padhya


7
Unit – 3 (ADO.Net)
system performance but requires the exclusive use of an open Connection object
for the lifetime of the DataReader
4. Data Adapter:
Finally, the DataAdapter provides the bridge between the DataSet object and the
data source. The DataAdapter uses Command objects to execute SQL commands
at the data source to both load the DataSet with data, and reconcile changes made
to the data in the DataSet back to the data source. The DataAdapter provides four
properties that represent database commands: SelectCommand InsertCommand
DeleteCommand UpdateCommand You can write .NET Framework data
providers for any data source. The .NET Framework ships with two .NET
Framework data providers: the .NET Framework Data Provider for SQL Server
and the .NET Framework Data Provider for OLE DB

What is Data Set:


The dataset is a disconnected, in-memory representation of data. It can be
considered as a local copy of the relevant portions of the database. The data in
DataSet can be loaded from any valid data source like Microsoft SQL server
database, an Oracle database or from a Microsoft Access database. It consist 2
types of collection, DataTableCollection & DataRelationCollection.
DataTableCollection : It contains 3 types of collection are as under,
(A) DataRowCollection • DataRowCollection contains a collection of DataRow
objects. • You can access & manipulate data in a DataTable‘s rows using a
DataRow object. • It use the Row collection to retrieve data, which is indexed by
row number (starting with 0).
(B) DataColumnCollection • DataColumnCollection contains a collection of
DataColumn objects. • It provides schema information about one of the columns
in a DataTable object.
(C) ConstraintCollection • ConstraintsCollection define what action to take
when data in a related column of a constituent row is altered. • There are two
types of constraints, ForeignKeyConstraints and UniqueConstraints.
DataRelationCollection : • DataRelationCollection is an instance of the
DataRelationCollection class. • The relations collection contains DataRelation
objects. • It is used to create parent-child relationships between DataTables in the

Creat By : kuldeep padhya


8
Unit – 3 (ADO.Net)
DataSet. • The example of this type of relation is the relationship of primary key–
foreign key

Data Set Class:


The dataset represents a subset of the database. It does not have a continuous
connection to the database. To update the database a reconnection is required.
The DataSet contains DataTable objects and DataRelation objects. The
DataRelation objects represent the relationship between two tables
Data Set Property:
Properties Description

CaseSensitive Indicates whether string comparisons


within the data tables are case-
sensitive.
Container Gets the container for the component.

DataSetName Gets or sets the name of the current


data set.
DefaultViewManager Returns a view of data in the data set.

DesignMode Indicates whether the component is


currently in design mode.
EnforceConstraints Indicates whether constraint rules are
followed when attempting any update
operation.
Events Gets the list of event handlers that are
attached to this component.
ExtendedProperties Gets the collection of customized user
information associated with the
DataSet.
HasErrors Indicates if there are any errors.

IsInitialized Indicates whether the DataSet is


initialized.
Locale Gets or sets the locale information
used to compare strings within the
table.
Namespace Gets or sets the namespace of the
DataSet.

Creat By : kuldeep padhya


9
Unit – 3 (ADO.Net)
Prefix Gets or sets an XML prefix that aliases
the namespace of the DataSet.
Relations Returns the collection of DataRelation
objects.
Tables Returns the collection of DataTable
objects.

Data Set Methods:

Methods Description

AcceptChanges Accepts all changes made since the DataSet


was loaded or this method was called.
BeginInit Begins the initialization of the DataSet. The
initialization occurs at run time.
Clear Clears data.

Clone Copies the structure of the DataSet,


including all
DataTable schemas, relations, and
constraints. Does not copy any data.
Copy Copies both structure and data.

CreateDataReader() Returns a DataTableReader with one result


set per
DataTable, in the same sequence as the
tables appear in the Tables collection.
CreateDataReader(DataTable) Returns a DataTableReader with one result
set per DataTable.
EndInit Ends the initialization of the data set.

Equals(Object) Determines whether the specified Object is


equal to the current Object.
Finalize Free resources and perform other cleanups.

GetChanges Returns a copy of the DataSet with all


changes made since it was loaded or the
AcceptChanges method was called.
GetChanges(DataRowState) Gets a copy of DataSet with all changes
made since it was loaded or the

Creat By : kuldeep padhya


10
Unit – 3 (ADO.Net)
AcceptChanges method was called, filtered
by DataRowState.
GetDataSetSchema Gets a copy of XmlSchemaSet for the
DataSet.
GetObjectData Populates a serialization information object
with the data needed to serialize the
DataSet.
GetType Gets the type of the current instance.

GetXML Returns the XML representation of the data.

GetXMLSchema Returns the XSD schema for the XML


representation of the data.
HasChanges() Gets a value indicating whether the DataSet
has changes, including new, deleted, or
modified rows.
HasChanges(DataRowState) Gets a value indicating whether the DataSet
has changes, including new, deleted, or
modified rows, filtered by DataRowState.
IsBinarySerialized Inspects the format of the serialized
representation of the DataSet.
Load(IDataReader, LoadOption, Fills a DataSet with values from a data
DataTable[]) source using the supplied IDataReader,
using an array of DataTable instances to
supply the schema and namespace
information

Data Set Events:


Events Description
Load(IDataReader, LoadOption, Fills a DataSet with values from a data
String[]) source using the supplied IDataReader,
using an array of strings to supply the names
for the tables within the DataSet.
Merge() Merges the data with data from another
DataSet. This method has different
overloaded forms.
ReadXML() Reads an XML schema and data into the
DataSet. This method has different
overloaded forms.

Creat By : kuldeep padhya


11
Unit – 3 (ADO.Net)
ReadXMLSchema(0) Reads an XML schema into the DataSet.
This method has different overloaded
forms.
RejectChanges Rolls back all changes made since the last
call to AcceptChanges.
WriteXML() Writes an XML schema and data from the
DataSet. This method has different
overloaded forms.
WriteXMLSchema() Writes the structure of the DataSet as an
XML schema. This method has different
overloaded forms.

Data Row Class


The DataRow object represents a row in a table. It has the following important
properties:
Properties Description

HasErrors Indicates if there are any errors.

Items Gets or sets the data stored in a specific


column.
ItemArrays Gets or sets all the values for the row.

Table Returns the parent table.

AcceptChanges Accepts all changes made since this method


was called.
BeginEdit Begins edit operation.

CancelEdit Cancels edit operation.

Delete Deletes the DataRow.

EndEdit Ends the edit operation.

GetChildRows Gets the child rows of this row.

GetParentRow Gets the parent row.

GetParentRows Gets parent rows of DataRow object.

Creat By : kuldeep padhya


12
Unit – 3 (ADO.Net)
RejectChanges Rolls back all changes made since the last
call to AcceptChanges.
EndEdit Ends the edit operation.

Data Adapter:
The DataAdapter provides the bridge between the DataSet object and the data
source. The DataAdapter uses Command objects to execute SQL commands at
the data source to both load the DataSet with data, and reconcile changes made
to the data in the DataSet back to the data source. The DataAdapter provides four
properties that represent database commands: SelectCommand InsertCommand
DeleteCommand UpdateCommand You can write .NET Framework data
providers for any data source. The .NET Framework ships with two .NET
Framework data providers: the .NET Framework Data Provider for SQL Server
and the .NET Framework Data Provider for OLE DB
As you start working data adapters, you need take a Quick looks at data adapter
properties and methods. The DataAdapter has properties of type Command,
which represent the ways it can query, insert, delete, and update the database.
Data Adapter Properties:
These properties are of type OleDbCommand.
PROPERTY DESCRIPTION

DeleteCommand Represents a DELETE statement or stored procedure for


deleting records from the data source
InsertCommand Represents an INSERT statement or stored procedure for
inserting a new record to The data source
SelectCommand Represents a SELECT statement or stored procedure can
be used to select records from a data source
UpdateCommand Represents an UPDATE statement or stored procedure
for Updating recording in a data source
TableMappings Represents a collection of mappings between actual data
source table and a DataTable object
SelectCommand cmd.SelectCommand.CommandText = "SELECT *
FROM Orders
ORDER BY Price";
DeleteCommand TheDataSetCommand.DeleteCommand.CommandText
= "DELETE
FROM orders WHERE LastName = 'Smith' ";

Creat By : kuldeep padhya


13
Unit – 3 (ADO.Net)
InsertCommand TheDataSetCommand.InsertCommand.CommandText
= "INSERT
INTO Orders VALUE (25, 'Widget1', 'smith')";
UpdateCommand TheDataSetCommand.UpdateCommand.CommandText
= "UPDATE
Orders SET ZipCode = '34956' WHERE OrderNum =
14";

Data Adapter Methods:


The DataAdapter class provides many useful methods. For instance, the FILL
method of the DataAdapter fills data from a data adapter to the DataSet object,
and the Update method stores data from a DataSet object to the data source.
The ole Db Data Adapter methods
METHOD DESCRIPTION

Fill This method fills data records from a DataAdapter to a


DataSet object.
FillSchema This method adds a DataTable to a DataSet.

GetFillParameters This method retrieves parameters that are ed when a


SELECT statement is executed.
Update This method stores data from a data set to the data
source.

Creat By : kuldeep padhya


14
Unit – 3 (ADO.Net)

Data Gridview :
Data GridView is a control used to display data in tables on a web page. It
displays data in both rows and columns, where each column represents a field,
and each row represents a record
GridView helps to perform key activities like Insert, Delete, Sorting, and Paging.
The DataGridView control provides a powerful and flexible way to display data
in a tabular format. You can use the DataGridView control to show read-only
views of a small amount of data, or you can scale it to show editable views of
very large sets of data
Data Gridview Property:
Property Description
AccessibilityObject Gets the AccessibleObject assigned to the
control.
AllowUserToDeleteRows Gets or sets a value indicating whether the user is
allowed to delete rows from the DataGridView.
AllowUserToOrderColum Gets or sets a value indicating whether manual
ns column repositioning is enabled.
AutoGenerateColumns Gets or sets a value indicating whether columns
are created automatically when
the DataSource or DataMember properties are
set.
AutoSize This property is not relevant for this class.
BackColor Gets or sets the background color for the control.
BackgroundColor Gets or sets the background color of
the DataGridView.
BackgroundImage Gets or sets the background image displayed in
the control.
BackgroundImageLayout Gets or sets the background image layout as
defined in the ImageLayout enumeration.
BorderStyle Gets or sets the border style for
the DataGridView
CausesValidation Gets or sets a value indicating whether the
control causes validation to be performed on any
controls that require validation when it receives
focus.

Creat By : kuldeep padhya


15
Unit – 3 (ADO.Net)
(Inherited from Control)
CellBorderStyle Gets the cell border style for the DataGridView.
ColumnCount Gets or sets the number of columns displayed in
the DataGridView.
ColumnHeadersBorderSty Gets the border style applied to the column
le headers.
ColumnHeadersDefaultCe Gets or sets the default column header style.
llStyle
ColumnHeadersHeight Gets or sets the height, in pixels, of the column
headers row.
DataBindings Gets the data bindings for the control.
(Inherited from Control)
DataContext Gets or sets the data context for the purpose of
data binding. This is an ambient property.
(Inherited from Control)
DataMember Gets or sets the name of the list or table in the
data source for which the DataGridView is
displaying data.
DataSource Gets or sets the data source that
the DataGridView is displaying data for.
EditingControl Gets the control hosted by the current cell, if a
cell with an editing control is in edit mode.
EditingPanel Gets the panel that contains the EditingControl.
EditMode Gets or sets a value indicating how to begin
editing a cell.
Focused Gets a value indicating whether the control has
input focus.
(Inherited from Control)
Font Gets or sets the font of the text displayed by
the DataGridView.
FontHeight Gets or sets the height of the font of the control.
(Inherited from Control)
ForeColor Gets or sets the foreground color of
the DataGridView.
GridColor Gets or sets the color of the grid lines separating
the cells of the DataGridView.
Height Gets or sets the height of the control.
(Inherited from Control)
HorizontalScrollBar Gets the horizontal scroll bar of the control.
IsCurrentCellDirty Gets a value indicating whether the current cell
has uncommitted changes.

Creat By : kuldeep padhya


16
Unit – 3 (ADO.Net)
IsCurrentCellInEditMode Gets a value indicating whether the currently
active cell is being edited.
IsCurrentRowDirty Gets a value indicating whether the current row
has uncommitted changes.
IsDisposed Gets a value indicating whether the control has
been disposed of.
(Inherited from Control)
IsHandleCreated Gets a value indicating whether the control has a
handle associated with it.
(Inherited from Control)
MaximumSize Gets or sets the size that is the upper limit
that GetPreferredSize(Size) can specify.
(Inherited from Control)
MinimumSize Gets or sets the size that is the lower limit
that GetPreferredSize(Size) can specify.
Name Gets or sets the name of the control.
(Inherited from Control)
Size Gets or sets the height and width of the control.
(Inherited from Control)
SortedColumn Gets the column by which
the DataGridView contents are currently sorted.
TabIndex Gets or sets the tab order of the control within its
container.
(Inherited from Control)
TabStop Gets or sets a value indicating whether the user
can give the focus to this control using the TAB
key.
(Inherited from Control)
Text Gets or sets the text associated with the control.
UserSetCursor Gets the default or user-specified value of
the Cursor property.
UseWaitCursor Gets or sets a value indicating whether to use the
wait cursor for the current control and all child
controls.
Visible Gets or sets a value indicating whether the
control and all its child controls are displayed.
(Inherited from Control)
Width Gets or sets the width of the control.
(Inherited from Control)
WindowTarget This property is not relevant for this class.

Creat By : kuldeep padhya


17
Unit – 3 (ADO.Net)

Data Gridview Method:


Method Description
AutoResizeRows() Adjusts the heights of all rows to fit the
contents of all their cells, including the
header cells.
BringToFront() Brings the control to the front of the z-
order.
(Inherited from Control)
CancelEdit() Cancels edit mode for the currently
selected cell and discards any changes.
ClearSelection() Clears the current selection by
unselecting all selected cells.
Dispose() Releases all resources used by
the Component.
FindForm() Retrieves the form that the control is
on.
(Inherited from Control)
Focus() Sets input focus to the control.
GetPreferredSize(Size) Retrieves the size of a rectangular area
into which a control can be fitted.
GetType() Gets the Type of the current instance.
Hide() Conceals the control from the user.
InitLayout() Called after the control has been added
to another container.
(Inherited from Control)
Invalidate() Invalidates the entire surface of the
control and causes the control to be
redrawn.
IsInputChar(Char) Determines whether a character is an
input character that
the DataGridView recognizes.
IsInputKey(Keys) Determines whether the specified key is
a regular input key or a special key that
requires preprocessing.
OnAutoSizeChanged(EventArgs) Raises the AutoSizeChanged event.
OnBorderStyleChanged(EventArgs) Raises the BorderStyleChanged event.
OnClick(EventArgs) Raises the Click event.
OnGotFocus(EventArgs) Raises the GotFocus event.

Creat By : kuldeep padhya


18
Unit – 3 (ADO.Net)
Refresh() Forces the control to invalidate its client
area and immediately redraw itself and
any child controls.
SelectAll() Selects all the cells in
the DataGridView.
Show() Displays the control to the user.
ToString() Returns a String containing the name of
the Component, if any. This method
should not be overridden.
(Inherited from Component)
Update() Causes the control to redraw the
invalidated regions within its client area.
UpdateStyles() Forces the assigned styles to be
reapplied to the control.

Data Gridview Event:


Event Description
AutoSizeChanged This event is not relevant for this class.
BackColorChanged Occurs when the value of
the BackColor property changes.
CausesValidationChanged Occurs when the value of
the CausesValidation property changes.
CellMouseEnter Occurs when the mouse pointer enters a
cell.
CellMouseLeave Occurs when the mouse pointer leaves a
cell.
CellMouseMove Occurs when the mouse pointer moves
over the DataGridView control.
CellMouseUp Occurs when the user releases a mouse
button while over a cell.
Click Occurs when the control is clicked.
DataSourceChanged Occurs when the value of
the DataSource property changes.
Disposed Occurs when the component is disposed
by a call to the Dispose() method.
Enter Occurs when the control is entered.
(Inherited from Control)
FontChanged Occurs when the Font property value
changes.

Creat By : kuldeep padhya


19
Unit – 3 (ADO.Net)
ForeColorChanged Occurs when the ForeColor property
value changes.
GotFocus Occurs when the control receives focus.
Invalidated Occurs when a control's display requires
redrawing.
Leave Occurs when the input focus leaves the
control.
LostFocus Occurs when the control loses focus.
MouseClick Occurs when the control is clicked by
the mouse.
MouseDoubleClick Occurs when the control is double
clicked by the mouse.
(Inherited from Control)
MouseDown Occurs when the mouse pointer is over
the control and a mouse button is
pressed.
(Inherited from Control)
MouseEnter Occurs when the mouse pointer enters
the control.
MouseHover Occurs when the mouse pointer rests on
the control.
PreviewKeyDown Occurs before the KeyDown event
when a key is pressed while focus is on
this control.
Resize Occurs when the control is resized.
Scroll Occurs when the user scrolls through
the control contents.
SelectionChanged Occurs when the current selection
changes.
SizeChanged Occurs when the Size property value
changes.
TabIndexChanged Occurs when the TabIndex property
value changes.
TextChanged Occurs when the value of
the Text property changes.
UserAddedRow Occurs when the user has finished
adding a row to
the DataGridView control.
UserDeletedRow Occurs when the user has finished
deleting a row from the

Creat By : kuldeep padhya


20
Unit – 3 (ADO.Net)
Validated Occurs when the control is finished
validating.
(Inherited from Control)
Validating Occurs when the control is validating.
(Inherited from Control)
VisibleChanged Occurs when the Visible property value
changes.

Creat By : kuldeep padhya

You might also like