Unit IV

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

UNIT 4 ASP.

NET Notes

Architecture of ADO.NET:
The .NET Framework Data Providers are components that have been explicitly designed for data
manipulation and fast, forward-only, read-only access to data. The Connection object provides connectivity
to a data source. The Command object enables access to database commands to return data, modify data, run
stored procedures, and send or retrieve parameter information. The DataReader provides a high-performance
stream of data from the data source. 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 that were made to the data in the DataSet back to
the data source.
The full form of ADO.NET is ActiveX Data Object.Net. Basically it is container of
all the standard classes which are responsible for database connectivity of .net
application to the any kind of third party database software like Ms Sql Server, Ms
Access, MySql, Oracle or any other database software.
All classes belongs to ADO.NET are defined and arrange in “System.Data” namespace.
The architecture of ADO.NET is following.

From above diagram it is clear that ADO.NET contain following important components. 1.
Connection
2. Command
3. DataReader
4. DataAdapter
5. Dataset

1. Connection: This component of Ado.net is responsible to connect our .net application with
any data source like Ms sql server database.

2. Command: This component contain classes for executing any INSERT, UPDATE, DELETE AND
SELECT command over database software using active connection.

Page|1
UNIT 4 ASP.NET Notes

3. DataReader: This component contains classes that capable to hold reference of records that
retrieved by Command class after executing SELECT Query.

4. Data Adapter: This component is capable to perform the entire task like executing INSERT,
UPDATE, DELETE and SELECT command on give Connection. The most important use of this
component is executing SELECT query for a number of records and fill up to Dataset components.

5. Dataset: This component is the main source of records for .net control like GridView. It has
capability to generate a number of tables to hold records retrieved from DataAdapter or XML.

Data provider for ADO.NET


Data provider is used to connect to the database, execute commands and retrieve
the record. It is lightweight component with better performance. It also allows us to place
the data into DataSet to use it further in our application.

A .NET Framework data provider is used for connecting to a database, executing


commands, and retrieving results. Those results are either processed directly, placed in
a DataSet in order to be exposed to the user as needed, combined with data from multiple
sources, or remoted between tiers. .NET Framework data providers are lightweight, creating
a minimal layer between the data source and code, increasing performance without
sacrificing functionality.

The .NET Framework provides the following data providers that we can use in our
application.

.NET Framework data provider Description

.NET Framework Data Provider for It provides data access for Microsoft SQL Server. It requires
SQL Server the System.Data.SqlClient namespace.

.NET Framework Data Provider for It is used to connect with OLE DB. It requires
OLE DB the System.Data.OleDb namespace.

.NET Framework Data Provider for It is used to connect to data sources by using ODBC. It
ODBC requires the System.Data.Odbc namespace.

.NET Framework Data Provider for It is used for Oracle data sources. It uses
Oracle the System.Data.OracleClient namespace.

EntityClient Provider It provides data access for Entity Data Model applications. It
requires the System.Data.EntityClient namespace.

Page|2
UNIT 4 ASP.NET Notes

.NET Framework Data Provider for It provides data access for Microsoft SQL Server Compact
SQL Server Compact 4.0. 4.0. It requires the System.Data.SqlServerCe namespace.

Connecting to data sources


A data source control interacts with the data-bound controls and hides the complex
data binding processes. These are the tools that provide data to the data bound
controls and support execution of operations like insertions, deletions, sorting, and
updates.
Each data source control wraps a particular data provider-relational databases,
XML documents, or custom classes and helps in:

• Managing connection
• Selecting data
• Managing presentation aspects like paging, caching, etc.
• Manipulating data
There are many data source controls available in ASP.NET for accessing data from
SQL Server, from ODBC or OLE DB servers, from XML files, and from business
objects.
Based on type of data, these controls could be divided into two categories:

• Hierarchical data source controls


• Table-based data source controls
The data source controls used for hierarchical data are:
• XMLDataSource - It allows binding to XML files and strings with or without
schema information.
• SiteMapDataSource - It allows binding to a provider that supplies site map
information.
The data source controls used for tabular data are:

Data source controls Description

SqlDataSource It represents a connection to an ADO.NET data provider that


returns SQL data, including data sources accessible via
OLEDB and ODBC.

ObjectDataSource It allows binding to a custom .Net business object that returns


data.

LinqdataSource It allows binding to the results of a Linq-to-SQL query


(supported by ASP.NET 3.5 only).

Page|3
UNIT 4 ASP.NET Notes

AccessDataSource It represents connection to a Microsoft Access database.

The SqlDataSource Control


The SqlDataSource control represents a connection to a relational database such
as SQL Server or Oracle database, or data accessible through OLEDB or Open
Database Connectivity (ODBC). Connection to data is made through two important
properties ConnectionString and ProviderName.
The following code snippet provides the basic syntax of the control:
<asp:SqlDataSource runat="server" ID="MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'
ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
SelectionCommand= "SELECT * FROM EMPLOYEES" />

<asp:GridView ID="GridView1" runat="server" DataSourceID="MySqlSource" />


Configuring various data operations on the underlying data depends upon the
various properties (property groups) of the data source control.
The following table provides the related sets of properties of the SqlDataSource
control, which provides the programming interface of the control:

Property Group Description

Gets or sets the SQL statement, parameters, and type for


DeleteCommand,
deleting rows in the underlying data.
DeleteParameters,
DeleteCommandType

Gets or sets the data filtering string and parameters.


FilterExpression,
FilterParameters

Gets or sets the SQL statement, parameters, and type for


InsertCommand,
inserting rows in the underlying database.
InsertParameters,
InsertCommandType

Gets or sets the SQL statement, parameters, and type for


SelectCommand,
retrieving rows from the underlying database.
SelectParameters,
SelectCommandType

Page|4
UNIT 4 ASP.NET Notes

SortParameterName Gets or sets the name of an input parameter that the


command's stored procedure will use to sort data.

Gets or sets the SQL statement, parameters, and type for


UpdateCommand,
updating rows in the underlying data store.
UpdateParameters,
UpdateCommandType

The following code snippet shows a data source control enabled for data
manipulation:
<asp:SqlDataSource runat="server" ID= "MySqlSource"
ProviderName='<%$ ConnectionStrings:LocalNWind.ProviderName %>'
ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
SelectCommand= "SELECT * FROM EMPLOYEES"
UpdateCommand= "UPDATE EMPLOYEES SET LASTNAME=@lame"
DeleteCommand= "DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid"
FilterExpression= "EMPLOYEEID > 10">
.....
.....
</asp:SqlDataSource>

The ObjectDataSource Control


The ObjectDataSource Control enables user-defined classes to associate the
output of their methods to data bound controls. The programming interface of this
class is almost same as the SqlDataSource control.
Following are two important aspects of binding business objects:
• The bindable class should have a default constructor, it should be stateless,
and have methods that can be mapped to select, update, insert, and delete
semantics.
• The object must update one item at a time, batch operations are not
supported.
Let us go directly to an example to work with this control. The student class is the
class to be used with an object data source. This class has three properties: a
student id, name, and city. It has a default constructor and a GetStudents method
for retrieving data.
The student class:
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public string City { get; set; }

public Student()

Page|5
UNIT 4 ASP.NET Notes

{}

public DataSet GetStudents()


{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Students");

dt.Columns.Add("StudentID", typeof(System.Int32));
dt.Columns.Add("StudentName", typeof(System.String));
dt.Columns.Add("StudentCity", typeof(System.String));
dt.Rows.Add(new object[] { 1, "M. H. Kabir", "Calcutta" });
dt.Rows.Add(new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
ds.Tables.Add(dt);

return ds;
}
}
Take the following steps to bind the object with an object data source and retrieve
data:
• Create a new web site.
• Add a class (Students.cs) to it by right clicking the project from the Solution
Explorer, adding a class template, and placing the above code in it.
• Build the solution so that the application can use the reference to the class.
• Place an object data source control in the web form.
• Configure the data source by selecting the object.

• Select a data method(s) for different operations on data. In this example,


there is only one method.

Page|6
UNIT 4 ASP.NET Notes

• Place a data bound control such as grid view on the page and select the
object data source as its underlying data source.

• At this stage, the design view should look like the following:

• Run the project, it retrieves the hard coded tuples from the students class.

Page|7
UNIT 4 ASP.NET Notes

The AccessDataSource Control


The AccessDataSource control represents a connection to an Access database. It
is based on the SqlDataSource control and provides simpler programming
interface. The following code snippet provides the basic syntax for the data source:
<asp:AccessDataSource ID="AccessDataSource1 runat="server"
DataFile="~/App_Data/ASPDotNetStepByStep.mdb" SelectCommand="SELECT * FROM
[DotNetReferences]">
</asp:AccessDataSource>
The AccessDataSource control opens the database in read-only mode. However, it
can also be used for performing insert, update, or delete operations. This is done
using the ADO.NET commands and parameter collection.
Updates are problematic for Access databases from within an ASP.NET application
because an Access database is a plain file and the default account of the
ASP.NET application might not have the permission to write to the database file.

Connection String and Connection Class


The first and essential part for data communication between .NET application and any database
software like Ms Sql Server is connection establishments between them.
The connection will established using driver name, data source file name and security options that
enclosed in string formats called connection string. It means right connection string is only
responsible for establishing connection with required database file.
In ASP.NET, connection string should be written in web.config file under root directory of web site
so that such connection string can be available to all code behind of web forms.
Let database.mdf is a Ms sql server database file created using inbuilt tools of Visual studio 2005.
Then the Format of connection string is written in web.config file as following.

<connectionStrings>
<add name="constr" connectionString="Data
Source= .\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Database.mdf
;
Integrated Security=True ;

Page|8
UNIT 4 ASP.NET Notes

User Instance=true"/>
</connectionStrings>

Connection String can be copy and paste from server explorer Select database property window copy
conection string.
In this web.config file connection string is enclosed in XML tag format.

Getting connection string on code behind:


Following namespace must be included in code behind of every page to get connection string.

using System.Configuration;

After then we declare a string variable to store connection string that getting from web.config file.
It is written as. string constr1= ConfigurationManager.
ConnectionStrings["constr"]. ConnectionString;

such connection string will enable connection with “Database.mdf” file that created using MS-SQL
Server database software.

Establishing Connection:
We need to connect our .NET application with required database file before data communication.
For this operation the connection must be opened and connection will be open by Connection Class
provided by ADO.NET. To estblising connection with different database file, we need Connection
Class.
Working with Connection Class:
Step 1: Create a connection string in web.config file.
Step 2: Include namespace: System.Data.SqlClient.
Step 3: Get Connection String in required Code Behind.
Step 4: Create Object of Connection Class and pass connection string to this object.
Step 5: Open connection.
Step 6: Perform data access operation.
Step 7: Close active connection.
Above steps can be implemented as.
Namespace: If we want to connect a Database.mdf file that created under MS-Sql Server Software
then Code Behind must included following namespace.
using System.Data.SqlClient;

Connection Class:
This namespace support following Connection Class to establishing connection.
SqlConnection

Page|9
UNIT 4 ASP.NET Notes

Before establishing connection, we need to create an connection object and passing connection string
to the constructor of Connection class like this-

SqlConnection con= new SqlConnection(constr1); here:


con = Connection object
constr1= a string variable that contain Connection String
Opening Connection: When Connection Object is created then by calling Open () method of
Connection Class, we can create an active connection.
Like-
con.Open();
When this method executes then connection will be established with required database file.
Closing Connection: When all data communication has been performed over this active connection,
then connection must be dis connected so that connection object can be further used with same
database file or different database file. Like-
con.Close();

Command Class:
This is one of component of ADO.NET. With the help of this componenet we can assign SQL
command and execute on database software using active connection.
SqlCommand
It is command class for MS-SQL Server Database.
Working process with Command Class:( for MS-SQL Server database) Step1: Include ADO.NET
namespace in code behind.

Ex: using System.Data.SqlClient ; Step2:


Open Database Connection.
Ex:
SqlConnection con=new SqlConnection(constr1); con.Open();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SQL command like INSERT / UPDATE / DELETE in string formate.
Ex:
To add new record
string sql= "INSERT INTO Book (BookName, Price) VALUES('ASP.NET',
500)";
To update new record
string sql= "UPDATE Book SET BookName= 'C#.NET', Price='400' WHERE
BookID=1";
To delete any record
string sql= "DELETE FROM Book WHERE BookID=1";

P a g e | 10
UNIT 4 ASP.NET Notes

Step4: Create Object of Command Class then Pass Sql Command and Active Connection to the
Constructor of command class.

Ex:
SqlCommand cmd = new SqlCommand(sql, con);
Here- sql= SQL Command in string form. con=
Active Connection.
Step5: Execute INSERT / UPDATE / DELETE Command using
ExecuteNonQuery() method of Command class.
Ex:
cmd.ExecuteNonQuery();
When all above steps are complete then required sql command will be executed on active connection
sucessfully.

Connection Pooling ADO.NET


ADO.NET uses a technique called connection pooling, which minimizes
the cost of repeatedly opening and closing connections. Connection pooling
reuses existing active connections with the same connection string instead of
creating new connections when a request is made to the database. It involves
the use of a connection manager that is responsible for maintaining a list, or
pool, of available connections for a given connection string. Several pools exist
if different connection strings ask for connection pooling.

You can turn off pooling for a specific connection by including the
Pooling=false key-value pair in your connection string. The SqlConnection class
also includes two methods ClearPool and ClearAllPools that let you clear its
associated pool or all pools currently managed by the provider within your
application respectively.

The following example shows a connection string with the connection pooling
option:

1. using System.Data.SqlClient;
2. namespace ConnectionPooling {
3. class Program {
4. static void Main(string[] args) {
5. string sqlConnectString = "Data Source=localhost;In
tegrated security=SSPI;Initial Catalog=AdventureWorks;";
6. SqlConnection connection = new SqlConnection();
7. // Set the connection string with pooling option

P a g e | 11
UNIT 4 ASP.NET Notes

8. connection.ConnectionString = sqlConnectString + "C


onnection Timeout=30;Connection Lifetime=0;Min Pool Size=0;Max
Pool Size=100;Pooling=true;";
9. //Open connection
10. connection.Open();
11. //Close connection
12. connection.Close();
13. }
14. }
15. }

A Connection String in the Web.Config file with connection pooling option:

1. <connectionStrings>
2. <clear />
3. <add name="sqlConnectionString" connectionString="Data Sou
rce=mySQLServer;Initial Catalog=myDatabase;Integrated Security=
True;Connection Timeout=15;Connection Lifetime=0;Min Pool Size=
0;Max Pool Size=100;Pooling=true;" />
4. </connectionStrings>

SQL Server connection string pooling attributes


• Connection Lifetime: Length of time in seconds after creation after which
a connection is destroyed. The default is 0, indicating that the connection
will have the maximum timeout.
• Connection Reset: Specifies whether the connection is reset when
removed from the pool. The default is true.
• Enlist: Specifies whether the connection is automatically enlisted in the
current transaction context of the creation thread if that transaction
context exists. The default is true.
• Load Balance Timeout: Length of time in seconds that a connection can
remain idle in a connection pool before being removed.
• Max Pool Size: Maximum number of connections allowed in the pool. The
default is 100.
• Min Pool Size: Minimum number of connections maintained in the pool.
The default is 0.
• Pooling: When true, the connection is drawn from the appropriate pool, or
if necessary, created and added to the appropriate pool. The default is
true.

P a g e | 12
UNIT 4 ASP.NET Notes

Perform Connection between Back end to front end.


ADO stands for active data object, which behaves as a mediator between the client side
and server side. Client side can’t directly interact with the server side, so there
is ADO.NET which behaves as a mediator between front end and back end as in the
following figure:

The preceding image shows the client-side application interacts with the server-side
application through ADO.NET which is behaving as a mediator between the front end and
back end.

Note: A programming language does not understand syntax and structure of other
programming language but if it is required to interact from one to another programming
language, there will be one mediator which will help them to interact without any
problem.

Connection-Oriented in ADO.NET

Before discussing ADO.NET connection orientation we will discuss what ADO.NET


contains.

P a g e | 13
UNIT 4 ASP.NET Notes

ADO.NET is a group of class which contains.

• Connection
• Command
• Datareader
• DataAdapter
• Dataset
Connection

Connection class used to establish the connection between the front end and back end:

1. SqlConnection con=new SqlConnection(“Integrated security=true;initial ca


talog=Student;Data source=.”);

Or

1. SqlConnection Con=new SqlConnection(“User id=sa;Password=sa123;Database=


Student;Server=.”);

Command

Command class behaves as a bridge between the front end and back end. It contains the
query which has to perform from the front end and back end and also it contains an
object of Connection Class:

1. SqlCommand cmd=new SqlCommand(“Query which has to perform”,Connection Ob


ject);

• DataReader: DataReader used to read the data from the source.


• Dataset: DataSet contains the table and relation.
• DataAdapter: DataAdapter behaves as a mediator between the back end and front
end. But it does not have features to contains the data. So there is a dataset that
contains the data of the result set.
In connection-oriented architecture the Database gets connected to the front end then the
command passes the query to the server from the back end and on the server the result
which has been generated. The result which has been generated will be read by
DataReader. Here's the screenshot:

Student.aspx

1. <%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="Student.a
spx.cs"Inherits="Iare.Student"%>

P a g e | 14
UNIT 4 ASP.NET Notes

2. <!DOCTYPE html>
3. <html
4. xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <styletype="text/css">
8. .auto-style1 {
9. width: 100%;
10. }
11.
12. </style>
13. </head>
14. <body style="height: 198px; width: 364px">
15. <form id="form1"runat="server">
16. <table class="auto-style1">
17. <tr>
18. <tdcolspan="2">
19. <asp:DropDownListID="DropDownList1"ru
nat="server"DataSourceID="Iare"DataTextField="SId"DataValueFiel
d="SId">
20. </asp:DropDownList>
21. <asp:SqlDataSourceID="Iare"runat="ser
ver"ConnectionString="<%$ ConnectionStrings:IareConnectionStrin
g %>"SelectCommand="SELECT [SId] FROM [Library]">
22. </asp:SqlDataSource>
23. </td>
24. </tr>
25. <tr>
26. <td>
27. <asp:LabelID="Label1"runat="server"Te
xt="Student First Name Is :">
28. </asp:Label>
29. </td>
30. <td>
31. <asp:TextBoxID="TextFName"runat="serv
er">
32. </asp:TextBox>
33. </td>
34. </tr>
35. <tr>
36. <td>
37. <asp:LabelID="Label2"runat="server"Te
xt="Student Last Name Is :">
38. </asp:Label>
39. </td>
40. <td>
41. <asp:TextBoxID="TextLName"runat="serv
er">

P a g e | 15
UNIT 4 ASP.NET Notes

42. </asp:TextBox>
43. </td>
44. </tr>
45. <tr>
46. <td>
47. <asp:LabelID="Label3"runat="server"Te
xt="Student Is Study :">
48. </asp:Label>
49. </td>
50. <td>
51. <asp:TextBoxID="TextCourse"runat="ser
ver">
52. </asp:TextBox>
53. </td>
54. </tr>
55. <tr>
56. <td>
57. <asp:LabelID="Lbldsply"runat="server"
>
58. </asp:Label>
59. </td>
60. <td>
61. <asp:ButtonID="Button1"runat="server"
OnClick="Button1_Click"Text="Save"/>
62. </td>
63. </tr>
64. </table>
65. <div></div>
66. </form>
67. </body>
68. </html>

P a g e | 16
UNIT 4 ASP.NET Notes

After designing the application go to Student.aspx.cs and write the following


code.

Student.aspx.cs

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. using System.Data;
8. using System.Data.SqlClient;
9. namespace Iare {
10. public partial classStudent: System.Web.UI.Page {
11. SqlConnection con = newSqlConnection("integrated secu
rity=true;Initial Catalog=Iare;Data Source=.");
12. SqlCommand cmd;
13. protected void Page_Load(object sender, EventArgs e)
{
14.
15. }
16.
17. protected void Button1_Click(object sender, EventArgs
e) {
18. string s = "insert into Student values(@p1,@p2,@p
3,@p4)";
19. con.Open();
20. cmd = newSqlCommand(s, con);
21. cmd.CommandType = CommandType.Text;
22. cmd.Parameters.AddWithValue("@p1", TextFName.Text
);
23. cmd.Parameters.AddWithValue("@p2", TextLName.Text
);
24. cmd.Parameters.AddWithValue("@p3", TextCourse.Tex
t);
25. cmd.Parameters.AddWithValue("@p4", DropDownList1.
SelectedItem.Value);
26. cmd.ExecuteNonQuery();
27. con.Close();
28. Lbldsply.Text = "Student Details Has Saved";
29. }
30. }
31. }

Now run the application and check.

P a g e | 17
UNIT 4 ASP.NET Notes

Executing commands:
ADO Data Reader:
Data Reader class in one of ADO.NET’s components. The purpose of this class is to hold the
reference of records that retived after executing SELECT command using ExecuteReader() method of
Command Class. SqlDataReader

It is a DataReader class for MS-SQL Server Database. Read() method of DataReader class will return
true value if records found otherwise false. Using index value(0,1,..) of DataReader object, we can
retieved column value of records.
Working process with DataReader Class:( for MS-SQL Server database) Step1: Include ADO.NET
namespace in code behind.

Ex: using System.Data.SqlClient ;


Step2: Open Database Connection.
Ex:
SqlConnection con = new SqlConnection(constr1); con.Open();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SELECT SQL command in string formate.
Ex:
string sql= "SELECT * FROM Book WHERE BookID=1";
Step4: Create Object of Command Class then Pass Sql Command and Active Connection to the
Constructor of command class.

Ex: SqlCommand cmd = new SqlCommand(sql, con);


Here- sql= SQL Command in string form.
con= Active Connection.
Step5: Create Object reference of DataReader class.

Ex: SqlDataReader dr;


Step6: Execute SELECT sql Command using ExecuteReader() method of Command class and assign
reference of retrieved records to the DataReader object reference.

Ex: dr=cmd.ExecuteReader();
Step7: Check availability of retirieved records in to DataReader using Read() method. If found then
retrives column's value into controls using idex value.
Ex:
if(dr.Read()==true)
{

TextBox1.Text=dr[0].ToString(); // First Column Value

P a g e | 18
UNIT 4 ASP.NET Notes

TextBox2.Text=dr[1].ToString(); // Second Column Value


TextBox3.Text=dr[2].ToString(); // Third Column Value
}
When all above steps are complete then required SELECT sql command will be executed on active
connection sucessfully and records will be shown on destination control.

Data Adapter and Dataset Class:


A Data Adapter represents a set of data commands and a database connection to fill the
dataset and update a SQL Server database.

A Data Adapter contains a set of data commands and a database connection to fill the
dataset and update a SQL Server database. Data Adapters form the bridge between a data
source and a dataset.

Data Adapters are designed depending on the specific data source. The following table
shows the Data Adapter classes with their data source.

Provider-Specific Data Adapter classes Data Source


SqlDataAdapter SQL Server
OledbDataAdapter OLE DB provider
OdbcDataAdapter ODBC driver
OracleDataAdapter Oracle

A Data Adapter supports mainly the following two methods:

• Fill (): The Fill method populates a dataset or a data table object with data from the
database. It retrieves rows from the data source using the SELECT statement
specified by an associated select command property.

The Fill method leaves the connection in the same state as it encountered before
populating the data.


Update (): The Update method commits the changes back to the database. It also
analyzes the RowState of each record in the DataSet and calls the appropriate
INSERT, UPDATE, and DELETE statements.
Example:
SqlDataAdapter da=new SqlDataAdapter("Select * from
Employee", con);
da.Fill(ds,"Emp");
bldr =new SqlCommandBuilder(da);
dataGridView1.DataSource = ds.Tables["Emp"];

P a g e | 19
UNIT 4 ASP.NET Notes

DataAdapter:
DataAdapter class of ADO.NET can be be used to execute any SQL comaand on given
connection and retrieved records can be filled into given Dataset.
SqlDataAdapter
It is a DataAdapter class for MS-SQL Server.
Fill() method of DataAdapter class that can be used to papulate dataset.
Dataset:
Dataset is a class of ADO.NET which is used to store records that retrieved from any
source like MS-SQL server, or XML files. When Dataset is papulated by records from any
source then records of Dataset can be shown on any Data bind control like GridView.
Working process with DataAdapter and Dataset Class:( for MS-SQL
Server database)
Step1: Include ADO.NET namespace in code behind.
Ex: using System.Data.SqlClient ;
Step2: Open Database Connection.
Ex:
SqlConnection con = new SqlConnection(constr1); con.Open();
Here constr1 is Connection String for required database connectivity.
Step3: Write Required SELECT SQL command in string formate.
Ex:
string sql= "SELECT * FROM Book";
Step4: Create Object of Command Class then Pass Sql Command and Active Connection
to the Constructor of command class.
Ex: SqlCommand cmd = new SqlCommand(sql, con);
Here- sql= SQL Command in string form.
con= Active Connection.
Step5: Create Object of DataAdapter class then pass object of Command Class to its
Constructur.
Ex: SqlDataAdapter da = new SqlDataAdapter (cmd);
Step6: Create Object of Dataset class.
Ex: Dataset ds = new Dataset();

P a g e | 20
UNIT 4 ASP.NET Notes

Step7: Call Fill() method of DataAdapter class and pass object of Dataset to fill retrived
records.
Ex: da.Fill(ds); Here-
Da=DataReader
ds= Dataset
When all above steps are complete then required SELECT sql command will be executed
on active connection successfully and records will be fillup into Dataset.

Data Bound Control and Data Grid ( GridView Control):


Any control of ASP.NET that can be used to show records of any data source like MS-
SQL Server called Data Bound Control. To Bind records on Data Bound control,
DataSource property and DataBind() method is used of that control.
Data Grid or GridView Control is one most papular and important Data bound control.
Using this control we can show records on table form. The Data source of GridView
control is Dataset.
Let GridView1 is one Databound control of GridView Control then to bind Records of
Dataset we have to apply DataSource property and
DataBind() method like.
GridView1.DataSource = ds;
GridView1.DataBind();
Here ds= Dataset with Records.
Working process with DataBound Control (
DataGrid / GridView) First add GridView Control on web page using following asp.net
code.
<asp: GridView ID= “GridView1” runat= “server” />
Now apply following steps on page load event of web page.
Step1 to Step7 are same as DataAdpter and Dataset.
Step8: Set Data source of GridView control that is Dataset.

Properties Description

CaseSensitive Indicates whether string comparisons within the data tables


are case-sensitive.

P a g e | 21
UNIT 4 ASP.NET Notes

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.

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.

Ex: GridView1.DataSource=ds;
Step9: Bind GridView control so that data can be shown on control.

P a g e | 22
UNIT 4 ASP.NET Notes

Ex: GridView1.DataBind();
When all above steps are completed then data of Dataset can be bindup to the data
bound control like Grid View.

DATASET

Data container objects: Data sets, Data tables, Data Relations

The Dataset 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.
Following table shows some important properties of the DataSet class:
The following table shows some important methods of the DataSet class:

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.

P a g e | 23
UNIT 4 ASP.NET Notes

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 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.

P a g e | 24
UNIT 4 ASP.NET Notes

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, Fills a DataSet with values from a data source using the supplied
LoadOption, DataTable[]) IDataReader, using an array of DataTable instances to supply the
schema and namespace information.

Load(IDataReader, Fills a DataSet with values from a data source using the supplied
LoadOption, String[]) 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.

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.

P a g e | 25
UNIT 4 ASP.NET Notes

WriteXMLSchema() Writes the structure of the DataSet as an XML schema. This


method has different overloaded forms.

The Data Table Class


The DataTable class represents the tables in the database. It has the following
important properties; most of these properties are read only properties except the
PrimaryKey property:

Properties Description

ChildRelations Returns the collection of child relationship.

Columns Returns the Columns collection.

Constraints Returns the Constraints collection.

DataSet Returns the parent DataSet.

DefaultView Returns a view of the table.

ParentRelations Returns the ParentRelations collection.

PrimaryKey Gets or sets an array of columns as the primary key for the table.

Rows Returns the Rows collection.

The following table shows some important methods of the DataTable class:

Methods Description

AcceptChanges Commits all changes since the last AcceptChanges.

Clear Clears all data from the table.

P a g e | 26
UNIT 4 ASP.NET Notes

GetChanges Returns a copy of the DataTable with all changes made since the
AcceptChanges method was called.

GetErrors Returns an array of rows with errors.

ImportRows Copies a new row into the table.

LoadDataRow Finds and updates a specific row, or creates a new one, if not
found any.

Merge Merges the table with another DataTable.

NewRow Creates a new DataRow.

RejectChanges Rolls back all changes made since the last call to
AcceptChanges.

Reset Resets the table to its original state.

Select Returns an array of DataRow objects.

The Data Reader Object


The DataReader object is an alternative to the DataSet and DataAdapter
combination. This object provides a connection oriented access to the data records
in the database. These objects are suitable for read-only access, such as populating
a list and then breaking the connection.

DB Command and DB Connection Objects


The DB Connection object represents a connection to the data source. The
connection could be shared among different command objects.
The DB Command object represents the command or a stored procedure sent to the
database from retrieving or manipulating data.

Example
So far, we have used tables and databases already existing in our computer. In this
example, we will create a table, add column, rows and data into it and display the
table using a GridView object.
The source file code is as given:

P a g e | 27
UNIT 4 ASP.NET Notes

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="createdatabase._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
<title>
Untitled Page
</title>
</head>

<body>
<form id="form1" runat="server">

<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>

</form>
</body>

</html>
The code behind file is as given:
namespace createdatabase
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
GridView1.DataSource = ds.Tables["Student"];
GridView1.DataBind();
}
}

private DataSet CreateDataSet()


{
//creating a DataSet object for tables
DataSet dataset = new DataSet();

// creating the student table


DataTable Students = CreateStudentTable();
dataset.Tables.Add(Students);

P a g e | 28
UNIT 4 ASP.NET Notes

return dataset;
}

private DataTable CreateStudentTable()


{
DataTable Students = new DataTable("Student");

// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "System.String", "StudentName");
AddNewColumn(Students, "System.String", "StudentCity");

// adding rows
AddNewRow(Students, 1, "M H Kabir", "Kolkata");
AddNewRow(Students, 1, "Shreya Sharma", "Delhi");
AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad");
AddNewRow(Students, 1, "Sunil Dubey", "Bikaner");
AddNewRow(Students, 1, "Rajat Mishra", "Patna");

return Students;
}

private void AddNewColumn(DataTable table, string columnType, string columnName)


{
DataColumn column = table.Columns.Add(columnName, Type.GetType(columnType));
}

//adding data into the table


private void AddNewRow(DataTable table, int id, string name, string city)
{
DataRow newrow = table.NewRow();
newrow["StudentID"] = id;
newrow["StudentName"] = name;
newrow["StudentCity"] = city;
table.Rows.Add(newrow);
}
}
}

P a g e | 29
UNIT 4 ASP.NET Notes

When the page is executed, it returns the rows of the table as shown:

QUESTIONS To PREPARE

Explain Architecture of ADO.NET in detail.


Evaluate Connection String and Connection Class with example.
Describe Working process with Data Adapter and Dataset Class with example.

Explain Data Reader Class with its steps and example.


Evaluate Working process with DataAdapter and Dataset Class:( for MS-SQLServer database)
Define: DataBound Control with example.
Discuss Data GridView.Control with example.
Describe Working process with Command Class with syntax.

Build a program to Display data on web form using Data bound controls.

Discuss working with transactions like insert and update command with its syntax.

Discuss working with transactions like Select and Delete command with its syntax.

Discuss data table in detail with example.

P a g e | 30

You might also like