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

ASP.NET_Unit6

The document provides an overview of ADO.NET, detailing its components, advantages, and data providers for various databases. It explains the architecture of ADO.NET, including Connection, Command, DataReader, DataAdapter, DataSet, and DataView, along with code examples for accessing and manipulating data using ASP.NET. Additionally, it covers working with stored procedures, XML, and XSLT for data transformation.

Uploaded by

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

ASP.NET_Unit6

The document provides an overview of ADO.NET, detailing its components, advantages, and data providers for various databases. It explains the architecture of ADO.NET, including Connection, Command, DataReader, DataAdapter, DataSet, and DataView, along with code examples for accessing and manipulating data using ASP.NET. Additionally, it covers working with stored procedures, XML, and XSLT for data transformation.

Uploaded by

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

Unit 6: Storing and Retrieving Data with ADO.

NET
❖ Introduction to ADO.NET
ADO.NET is a collection of classes that exposes data access services for the .NET
framework. It provides a rich set of components for creating distributed data sharing
applications. It contains a set of libraries that helps the user to interact with the data
sources.
Advantages of ADO.NET
⎯ It contains SQL Server Data Provider which is optimized for interaction with
SQL Server
⎯ It provides a good support for XML data
⎯ It provides disconnected operation model with Datasets
⎯ It has rich object model providing class inheritance and interface
implementation
ADO.NET contains data providers that allow user to interact with different type of
data sources and databases. There are several data providers in ADO.NET. Each has a
unique feature associated with it.
The table containing the list of providers is as shown below:
Data Provider Description
Data Provider for SQL It provides data access for Microsoft SQL Server.
Server The System.Data.SqlClient namespace is used
Data Provider for OLEDB It is used for data sources using OLE DB.
The System.Data.OleDb namespace is used
Data Provider for ODBC It is used for data sources using ODBC.
The System.Data.Odbc namespace is used
Data Provider for Oracle It is used Oracle data sources.
The System.Data.OracleClient namespace is used
EntityClient Provider It provides data access for Entity Data Model.
The System.Data.EntityClient namespace
Data Provider for SQL It provides data access for Microsoft SQL Server 4.0.
Server Compact 4.0 The System.Data.SqlServerCe namespace is used
The ADO.NET Architecture is comprised of 6 important components. They are
as follows:
1)Connection:
⎯ This component of ADO.NET Architecture is the Connection Object. The
Connection Object is required to connect with your backend database
which can be SQL Server, Oracle, MySQL, etc.

1
⎯ To create a connection object, you need at least two things. The first one
is where is your database located i.e. the Machine name or IP Address or
someplace where your database is located. And the second thing is the
security credentials i.e. whether it is a Windows authentication or SQL
Authentication i.e. user name and password-based authentication.
⎯ So, the first is to create the connection object and the connection object
is required to connect the front-end application with the backend data
source.

2)Command:
⎯ This component of ADO.NET Architecture is the Command Object. The
Command Object is the component where you write queries.
⎯ you take the command object and execute it over the connection. That
means using the command object, you can fetch data or send data to the
database i.e performing the Database CRUD Operations.

3)DataReader:
⎯ DataReader is a read-only connection-oriented record set that helps us to
read the records only in the forward mode. Here, you need to understand
three things i.e. read-only, connection-oriented, and forward mode.
Read-Only means using DataReader, we cannot Insert, Update, and
Delete the data.
⎯ Connection-Oriented means, it always requires an active and open
connection to fetch the data. Forward mode means you can always read
the next record, there is no way that you can read the previous record.

4)DataAdapter:
⎯ The DataAdapter is one of the Components of ADO.NET which acts as a
bridge between the command object and the dataset.
⎯ What the DataAdapter does is, it takes the data from the command object
and fills the data set.

5)DataSet:
⎯ It is a disconnected record set that can be browsed in both i.e. forward
and backward mode. It is not read-only i.e. you can update the data
present in the data set.
⎯ Actually, DataSet is a collection of DataTables that holds the data and we
can add, update, and delete data in a data table. DataSet gets filled by
somebody called DataAdapter.

2
6)DataView Class:
⎯ The DataView class enables us to create different views of the data
stored in a DataTable. This is most often used in data-binding applications.
⎯ Using a DataView, we can expose the data in a table with different sort
orders, and you can filter the data by row state or based on a filter
expression.

❖ Accessing Data with ADO.NET

Default2.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs"
Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<asp:DropDownList ID="ddlDesignation" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlDesignation_SelectedIndexChanged">
<asp:ListItem Text="Select Designation" Value="" />
<asp:ListItem Text="Manager" Value="Manager" />
<asp:ListItem Text="Developer" Value="Developer" />
<asp:ListItem Text="Designer" Value="Designer" />
</asp:DropDownList>
<br />
<br />
<asp:GridView ID="gvEmployees" runat="server"
AutoGenerateColumns="False" Width="400px">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" SortExpression="Id" />
<asp:BoundField DataField="name" HeaderText="Name"
SortExpression="Name" />

3
<asp:BoundField DataField="desg" HeaderText="Designation"
SortExpression="Designation" />
<asp:BoundField DataField="salary" HeaderText="Salary"
SortExpression="Salary" />
</Columns>
</asp:GridView>
<br />
</div>
</div>
</form>
</body>
</html>

Default2.aspx.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ddlDesignation_SelectedIndexChanged(object sender, EventArgs e)
{
DisplayEmployees(ddlDesignation.SelectedValue);
}

private void DisplayEmployees(string designation)


{
string connectionString = @"Data Source= COMP_LAB2;Initial
Catalog=EmpDataBase;Integrated Security=True";
string query = "SELECT id, name, desg, salary FROM Employee WHERE desg =
@desg";
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{

4
cmd.Parameters.AddWithValue("@desg", designation);
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
// Bind the result to the GridView
gvEmployees.DataSource = dataTable;
gvEmployees.DataBind();
}
}
}
}
}

❖ Working with DML commands

Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">

5
<div>
<asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Mobile No."></asp:Label>
<asp:TextBox ID="txtmno" runat="server" MaxLength="10"></asp:TextBox>
<br />
<br />
<asp:Label ID="lblmsg" runat="server" Text=""></asp:Label>
<br />
<br />
<asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />
<asp:Button ID="btnupdate" runat="server" Text="Update"
OnClick="btnupdate_Click" />
<asp:Button ID="btndelete" runat="server" Text="Delete"
OnClick="btndelete_Click" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="name" HeaderText="Name" />
<asp:BoundField DataField="mobileno" HeaderText="Mobile No." />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkselect" runat="server"
CommandArgument='<%# Eval("empid") %>'
OnClick="lnkselect_Click">Select</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView> </div>
</form>
</body>
</html>
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

6
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(@"Data Source= COMP_LAB2;Initial
Catalog=EmpDataBase;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
display();
}
}
protected void btnadd_Click(object sender, EventArgs e)
{
con.Open();
string str = "insert into Emp values('" + txtname.Text + "','" + txtmno.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
lblmsg.Text = "Record Inserted Successfully";
con.Close();
display();
cleartxt();
}
protected void lnkselect_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
Session["id"] = btn.CommandArgument;
con.Open();
SqlCommand cmd = new SqlCommand("select * from Emp", con);
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
if (dt.Rows.Count >= 0)
{
txtname.Text = dt.Rows[0]["name"].ToString();
txtmno.Text = dt.Rows[0]["mobileno"].ToString();
}
con.Close();
}
public void display()
{
con.Open();

7
SqlCommand cmd = new SqlCommand("select * from Emp", con);
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
protected void btnupdate_Click(object sender, EventArgs e)
{
con.Open();
string str = "update Emp set name='" + txtname.Text + "', mobileno='" +
txtmno.Text + "'where empid='" + Session["id"] + "'";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
lblmsg.Text = "Record Updated Successfully";
con.Close();
display();
}
protected void btndelete_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("delete from Emp where empid='" +
Session["id"] + "'", con);
cmd.ExecuteNonQuery();
lblmsg.Text = "Record Deleted";
con.Close();
display();
}
public void cleartxt()
{
txtmno.Text = "";
txtname.Text = "";
}
}
❖ Processing Transactions
Fetching total salary using stored procedure:
EmpDetails table:

8
CREATE PROCEDURE GetTotalSalary
AS
BEGIN
SELECT SUM(salary) AS TotalSalary FROM EmpDetails
END

StProcedure.aspx:

<div>
<h2>Employee Details</h2>
Name:
<asp:TextBox ID="txtname" runat="server"></asp:TextBox>
<br />
Salary:
<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnInsert" runat="server" Text="Insert Employee"
OnClick="btnInsert_Click" />
<br />
<br />
<asp:Button ID="btnGetTotalSalary" runat="server" Text="Get Total Salary"
OnClick="btnGetTotalSalary_Click" />
<br />
<asp:Label ID="lblMsg" runat="server" Text=""></asp:Label>
<br />
<asp:Label ID="lblTotalSalary" runat="server" Text=""></asp:Label>
</div>

9
StProcedure.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection con = new SqlConnection(@"Data Source=COMP_LAB2;Initial
Catalog=EmpDataBase;Integrated Security=True");

protected void btnInsert_Click(object sender, EventArgs e)


{
con.Open();
string str = "insert into EmpDetails values('" + txtname.Text + "','" +
txtSalary.Text + "')";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
lblMsg.Text = "Record Inserted Successfully";
con.Close();
}
protected void btnGetTotalSalary_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("GetTotalSalary", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader r = cmd.ExecuteReader();
if (r.Read())
{
decimal totalSalary = Convert.ToDecimal(r["TotalSalary"]);
lblTotalSalary.Text = "Total Salary: " + totalSalary.ToString();
}
r.Close();
}
❖ Data Sets on Web Forms
GridViewEx.aspx:
<div>
<asp:GridView ID="GridView1" runat="server"></asp:GridView></div>
GridViewEx.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{

10
DataSet ds = new DataSet();
DataTable dt = new DataTable() ;
DataRow dr;
DataColumn name;
DataColumn course;
DataColumn roll;
name = new DataColumn("Name", Type.GetType("System.String"));
course = new DataColumn("Course", Type.GetType("System.String"));
roll = new DataColumn("Roll", Type.GetType("System.Int32"));
dt.Columns.Add(name);
dt.Columns.Add(course);
dt.Columns.Add(roll);
dr = dt.NewRow();
dr["name"] = "A";
dr["course"] = "BCA";
dr["roll"] = 123;
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["name"] = "B";
dr["course"] = "BCS";
dr["roll"] = 321;
dt.Rows.Add(dr);

dr = dt.NewRow();
dr["name"] = "C";
dr["course"] = "BBA";
dr["roll"] = 111;
dt.Rows.Add(dr);

ds.Tables.Add(dt);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}

❖ XML & XSLT


⎯ XML use is widely spread in almost all the modern technologies including
.NET Framework that provides many useful classes to work with XML
Documents in System.Xml namespace. XML Documents contain raw data
without any formatting or presentation logic and developers use XSLT to
transform XML documents into other formats such as HTML.

11
⎯ To do this, develop a XSL file that has some rules to transform the XML data.
XSL language will use XPATH query to navigate through node elements and
attributes in XML documents. Also, it includes for-each loops, if statement, etc
similar to programming languages to assist the transformations.

Sample.xml:
<?xml version="1.0" encoding="utf-8" ?>
<Category>
<Products>
<ID>1</ID>
<Name>Product A</Name>
<Price>2500</Price>
</Products>
<Products>
<ID>2</ID>
<Name>Product B</Name>
<Price>2000</Price>
</Products>
<Products>
<ID>3</ID>
<Name>Product C</Name>
<Price>3000</Price>
</Products>
</Category>

XSLTFile.xslt
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="@* | node()">


<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/">
<xsl:for-each select="//Category//Products">
<div style="border:1px black solid;width:300px;margin:1px">
<div>
<b>ID:</b>
<xsl:value-of select="ID"/>

12
</div>
<div>
<b>Name:</b>s
<xsl:value-of select="Name"/>
</div>
<div>
<b>Price:</b>
<xsl:value-of select="Price"/>
</div>
</div>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

In the above code, <xsl:template match="/"> will return the root element (Category)
in XML file. The //products will select all the occurrence of products node under the
root element <Category> and converts the xml to HTML.

Default.aspx:
<div>
<asp:Xml ID="Xml1" runat="server" DocumentSource="~/Sample.xml"
TransformSource="~/XSLTFile.xslt" />
</div>

XSLT Transformation using ASP.Net


.Netframework includes a class called XslCompiledTransform in System.Xml.Xsl
namespace which can be used to perform the transformation. In specific, the
XslCompiledTransform class is packed with a method called
XslCompiledTransform.Transform() which can be used to the transformation.
The below code can be used to trasform a xml data from an XML file (sample.xml)
using the XSLT file(XSLTFile.xslt).
protected void Page_Load(object sender, EventArgs e)
{
string strXSLTFile = Server.MapPath("XSLTFile.xslt");
string strXMLFile = Server.MapPath("Sample.xml");

XmlReader reader = XmlReader.Create(strXMLFile);


XslCompiledTransform obj = new XslCompiledTransform();
obj.Load(strXSLTFile);
StringBuilder s = new StringBuilder();
TextWriter t = new StringWriter(s);
obj.Transform(reader, null, t);

13
Label1.Text = s.ToString();
reader.Close();
}
Default.aspx:
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>

14

You might also like