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

ASP.net Unit -III

The document provides an overview of data access and data binding in ASP.NET, detailing various data source controls such as SqlDataSource, ObjectDataSource, and AccessDataSource, along with their functionalities. It explains how these controls interact with data-bound controls to perform operations like insertion, deletion, and updates, while also discussing simple and declarative data binding methods. Additionally, it includes code snippets and examples for implementing these concepts in a web application.

Uploaded by

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

ASP.net Unit -III

The document provides an overview of data access and data binding in ASP.NET, detailing various data source controls such as SqlDataSource, ObjectDataSource, and AccessDataSource, along with their functionalities. It explains how these controls interact with data-bound controls to perform operations like insertion, deletion, and updates, while also discussing simple and declarative data binding methods. Additionally, it includes code snippets and examples for implementing these concepts in a web application.

Uploaded by

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

22UCSCC62 : DOTNET PROGRAMMING

Unit III: Performing data access Hours:15


using DataBound controls – using DataSource controls – using programmatic
DataBinding – understanding templates and DataBinding Expressions - Using the
SqlDataSource control: Creating database connections – executing database commands
– using ASP.NET parameters with the SqlDataSource Control – programmatically
executing SqlDataSource commands – catching database data with the SqlDataSource
control.
-----------------------------------------------------------------------------------------------------------

3.1DATA SOURCE

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

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


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

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

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 1
22UCSCC62 : DOTNET PROGRAMMING

It allows binding to the results of a Linq-to-SQL query (supported by


LinqdataSource
ASP.NET 3.5 only).

AccessDataSource It represents connection to a Microsoft Access database.

Data Source Views


Data source views are objects of the DataSourceView class. Which represent a customized view
of data for different data operations such as sorting, filtering, etc.

The DataSourceView class serves as the base class for all data source view classes, which define
the capabilities of data source controls.

The following table provides the properties of the DataSourceView class:

Properties Description

CanDelete Indicates whether deletion is allowed on the underlying data source.

CanInsert Indicates whether insertion is allowed on the underlying data source.

CanPage Indicates whether paging is allowed on the underlying data source.

CanRetrieveTotalRowCount Indicates whether total row count information is available.

CanSort Indicates whether the data could be sorted.

CanUpdate Indicates whether updates are allowed on the underlying data source.

Events Gets a list of event-handler delegates for the data source view.

Name Name of the view.

The following table provides the methods of the DataSourceView class:

Methods Description

Determines whether the specified command can be


CanExecute
executed.

ExecuteCommand Executes the specific command.

Performs a delete operation on the list of data that the


ExecuteDelete
DataSourceView object represents.

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 2
22UCSCC62 : DOTNET PROGRAMMING

Performs an insert operation on the list of data that the


ExecuteInsert
DataSourceView object represents.

ExecuteSelect Gets a list of data from the underlying data storage.

Performs an update operation on the list of data that the


ExecuteUpdate
DataSourceView object represents.

Performs a delete operation on the data associated with the


Delete
view.

Performs an insert operation on the data associated with the


Insert
view.

Select Returns the queried data.

Performs an update operation on the data associated with


Update
the view.

OnDataSourceViewChanged Raises the DataSourceViewChanged event.

Called by the RaiseUnsupportedCapabilitiesError method


RaiseUnsupportedCapabilitiesError to compare the capabilities requested for an ExecuteSelect
operation against those that the view supports.

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.

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 3
22UCSCC62 : DOTNET PROGRAMMING

The following table provides the related sets of properties of the SqlDataSource control, which
provides the programming interface of the control:

Property Group Description

DeleteCommand,
Gets or sets the SQL statement, parameters, and type for deleting rows in
DeleteParameters,
the underlying data.
DeleteCommandType

FilterExpression,
Gets or sets the data filtering string and parameters.
FilterParameters

InsertCommand,
Gets or sets the SQL statement, parameters, and type for inserting rows
InsertParameters,
in the underlying database.
InsertCommandType

SelectCommand,
Gets or sets the SQL statement, parameters, and type for retrieving rows
SelectParameters,
from the underlying database.
SelectCommandType

Gets or sets the name of an input parameter that the command's stored
SortParameterName
procedure will use to sort data.

UpdateCommand,
Gets or sets the SQL statement, parameters, and type for updating rows
UpdateParameters,
in the underlying data store.
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>

Explore our latest online courses and learn new skills at your own pace. Enroll and become a
certified exert to boost your career.

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 4
22UCSCC62 : DOTNET PROGRAMMING

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()
{}

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.
N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC
Page 5
22UCSCC62 : DOTNET PROGRAMMING

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

 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:

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 6
22UCSCC62 : DOTNET PROGRAMMING

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

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.

Print Page

3.2 DATA BINDING


Every ASP.NET web form control inherits the DataBind method from its parent Control class, which
gives it an inherent capability to bind data to at least one of its properties. This is known as simple
data binding or inline data binding.
N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC
Page 7
22UCSCC62 : DOTNET PROGRAMMING

Simple data binding involves attaching any collection (item collection) which implements the
IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the
control.

On the other hand, some controls can bind records, lists, or columns of data into their structure
through a DataSource control. These controls derive from the BaseDataBoundControl class. This is
called declarative data binding.

The data source controls help the data-bound controls implement functionalities such as, sorting,
paging, and editing data collections.

The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:

 DataBoundControl
 HierarchicalDataBoundControl

The abstract class DataBoundControl is again inherited by two more abstract classes:

 ListControl
 CompositeDataBoundControl

The controls capable of simple data binding are derived from the ListControl abstract class and these
controls are:

 BulletedList
 CheckBoxList
 DropDownList
 ListBox
 RadioButtonList

The controls capable of declarative data binding (a more complex data binding) are derived from the
abstract class CompositeDataBoundControl. These controls are:

 DetailsView
 FormView
 GridView
 RecordList

Simple Data Binding


Simple data binding involves the read-only selection lists. These controls can bind to an array list or
fields from a database. Selection lists takes two values from the database or the data source; one
value is displayed by the list and the other is considered as the value corresponding to the display.

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 8
22UCSCC62 : DOTNET PROGRAMMING

Let us take up a small example to understand the concept. Create a web site with a bulleted list and a
SqlDataSource control on it. Configure the data source control to retrieve two values from your
database (we use the same DotNetReferences table as in the previous chapter).

Choosing a data source for the bulleted list control involves:

 Selecting the data source control


 Selecting a field to display, which is called the data field
 Selecting a field for the value

When the application is executed, check that the entire title column is bound to the bulleted list and
displayed.

Declarative Data Binding

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 9
22UCSCC62 : DOTNET PROGRAMMING

We have already used declarative data binding in the previous tutorial using GridView control. The
other composite data bound controls capable of displaying and manipulating data in a tabular manner
are the DetailsView, FormView, and RecordList control.

In the next tutorial, we will look into the technology for handling database, i.e, ADO.NET.

However, the data binding involves the following objects:

 A dataset that stores the data retrieved from the database.


 The data provider, which retrieves data from the database by using a command over a connection.
 The data adapter that issues the select statement stored in the command object; it is also capable of
update the data in a database by issuing Insert, Delete, and Update statements.

Relation between the data binding objects:

Example
Let us take the following steps:

Step (1) : Create a new website. Add a class named booklist by right clicking on the solution name in
the Solution Explorer and choosing the item 'Class' from the 'Add Item' dialog box. Name it as
booklist.cs.

using System;
using System.Data;
using System.Configuration;
using System.Linq;

using System.Web;
using System.Web.Security;

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 10
22UCSCC62 : DOTNET PROGRAMMING

using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

namespace databinding
{
public class booklist
{
protected String bookname;
protected String authorname;
public booklist(String bname, String aname)
{
this.bookname = bname;
this.authorname = aname;

public String Book


{
get
{
return this.bookname;
}
set
{
this.bookname = value;
}
}

public String Author


{
get
{
return this.authorname;
}
set
{
this.authorname = value;
}
}
}
}

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 11
22UCSCC62 : DOTNET PROGRAMMING

Step (2) : Add four list controls on the page a list box control, a radio button list, a check box list,
and a drop down list and four labels along with these list controls. The page should look like this in
design view:

The source file should look as the following:

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


<div>

<table style="width: 559px">


<tr>
<td style="width: 228px; height: 157px;">
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
</td>

<td style="height: 157px">


<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>

<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 12
22UCSCC62 : DOTNET PROGRAMMING

<td style="height: 40px">


<asp:Label ID="lbldrpdown" runat="server">
</asp:Label>
</td>
</tr>

<tr>
<td style="width: 228px; height: 21px">
</td>

<td style="height: 21px">


</td>
</tr>

<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>

<td style="height: 21px">


<asp:CheckBoxList ID="CheckBoxList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
</td>
</tr>

<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>

<td style="height: 21px">


<asp:Label ID="lblchklist" runat="server">
</asp:Label>
</td>
</tr>
</table>

</div>
</form>

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 13
22UCSCC62 : DOTNET PROGRAMMING

Step (3) : Finally, write the following code behind routines of the application:

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


{
protected void Page_Load(object sender, EventArgs e)
{
IList bklist = createbooklist();

if (!this.IsPostBack)
{
this.ListBox1.DataSource = bklist;
this.ListBox1.DataTextField = "Book";
this.ListBox1.DataValueField = "Author";

this.DropDownList1.DataSource = bklist;
this.DropDownList1.DataTextField = "Book";
this.DropDownList1.DataValueField = "Author";

this.RadioButtonList1.DataSource = bklist;
this.RadioButtonList1.DataTextField = "Book";
this.RadioButtonList1.DataValueField = "Author";

this.CheckBoxList1.DataSource = bklist;
this.CheckBoxList1.DataTextField = "Book";
this.CheckBoxList1.DataValueField = "Author";

this.DataBind();
}
}

protected IList createbooklist()


{
ArrayList allbooks = new ArrayList();
booklist bl;

bl = new booklist("UNIX CONCEPTS", "SUMITABHA DAS");


allbooks.Add(bl);

bl = new booklist("PROGRAMMING IN C", "RICHI KERNIGHAN");


allbooks.Add(bl);

bl = new booklist("DATA STRUCTURE", "TANENBAUM");


allbooks.Add(bl);

bl = new booklist("NETWORKING CONCEPTS", "FOROUZAN");


allbooks.Add(bl);

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 14
22UCSCC62 : DOTNET PROGRAMMING

bl = new booklist("PROGRAMMING IN C++", "B. STROUSTROUP");


allbooks.Add(bl);

bl = new booklist("ADVANCED JAVA", "SUMITABHA DAS");


allbooks.Add(bl);

return allbooks;
}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lbllistbox.Text = this.ListBox1.SelectedValue;
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lbldrpdown.Text = this.DropDownList1.SelectedValue;
}

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lblrdlist.Text = this.RadioButtonList1.SelectedValue;
}

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lblchklist.Text = this.CheckBoxList1.SelectedValue;
}
}

Observe the following:

 The booklist class has two properties: bookname and authorname.


 The createbooklist method is a user defined method that creates an array of booklist objects named
allbooks.
 The Page_Load event handler ensures that a list of books is created. The list is of IList type, which
implements the IEnumerable interface and capable of being bound to the list controls. The page load
event handler binds the IList object 'bklist' with the list controls. The bookname property is to be
displayed and the authorname property is considered as the value.
 When the page is run, if the user selects a book, its name is selected and displayed by the list controls
whereas the corresponding labels display the author name, which is the corresponding value for the
selected index of the list control.

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 15
22UCSCC62 : DOTNET PROGRAMMING

3.3 Architecture of ADO.NET:


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.

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 16
22UCSCC62 : DOTNET PROGRAMMING

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

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 17
22UCSCC62 : DOTNET PROGRAMMING

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 ;

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

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 18
22UCSCC62 : DOTNET PROGRAMMING

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

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);

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 19
22UCSCC62 : DOTNET PROGRAMMING

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

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 20
22UCSCC62 : DOTNET PROGRAMMING

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

DataReader Class:
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
N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC
Page 21
22UCSCC62 : DOTNET PROGRAMMING

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 TextBox2.Text=dr[1].ToString(); //


Second Column Value TextBox3.Text=dr[2].ToString(); // Third Column Value

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 22
22UCSCC62 : DOTNET PROGRAMMING

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 Datset Class:


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.

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 23
22UCSCC62 : DOTNET PROGRAMMING

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();
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 sucessfully and records will befillup 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
N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC
Page 24
22UCSCC62 : DOTNET PROGRAMMING

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. Ex:
GridView1.DataSource=ds;

Step9: Bind GridView control so that data can be shown on control.


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

N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC


Page 25

You might also like