ASP Unit3
ASP Unit3
DataReader
DataAdapter
DataSet
Command Class :-
Properties of Command object:
1) Connection: It provides the information regarding the connection object
that you are using for connecting with database that connection should be
open for executing commands.
2) Command Text: it provides the SQL query that will be fired such as
insert, update, delete or select command.
3) Connection Type: It is used to set or get the type of command object. It
can be either text or store procedure.
4) Command Timeout: It allows you to get or set the timeout period for
command object.
5) Parameters: It used to specify the parameters that would be passed in the
parameterized query. It can set while using symbol @.
Ex: String q=”select * from table_name where id=@id”;
6) Parameters count: It give total no of parameters specify in the command
text.
Method of SQL Command object:
1) executeNonQuery(): This method is used when you are using
transactional queries like insert, update or delete. It return integer values
as return value indicating the total no of rows affected by the given query.
2) executeReader(): This method is used read the data from table using
select query.
3) executeScaler(): This method is used to execute the query and return the
first column of first row in the result set return by the query. Additional
columns or row will be ignoring. It is used with aggregate function.
Aggrigate functions like max(), min(), avg(), sum() and count().
4) executeXMLReader(): This method is used to read the data in XML
format when you are using XML file.
5) createParameter(): It is used to create parameter. After creation of
parameters, the parameters would be added to a parameter collections.
Connection:
String str=”select * from emp;”
SqlConnection con=new SqlConnction(“@path”);
SqlCommand cmd=new SqlCommand(str, con);
cmd.connection=con;
Command text:
String str=”select * from emp”;
SqlConnection con=new SqlConnection(“@path”);
SqlCommand cmd=new SqlCommand(str,con);
cmd.Connection =con;
cmd.CommandText=str;
Data Adapter Class :-
- It is associated command and connection object.
- The data Adapter is the class at the core of ADO.NET’s disconnected
data access.
- It is the mediator or bridge between the database and dataset.
- The data adapter provides set of methods and properties to retrieve and
save data between dataset and database.
- The data adapter is used to fill method to fill a data table or dataset.
- The data adapter can commit the changes to the database by its update
method.
- The data adapter provides four properties that represent database
command.
o Select
o Insert
o Update
o Delete
Properties of Data Adapter:
1) Insert: This property is used to generate insert command automatically,
if you have inserted some new row in the dataset or data table SQL
command builder automatically generate insert command and update a
final database.
2) Update: This property is used to generate update command
automatically, if you have updated some new row in the dataset or data
table SQL command builder automatically generate update command and
update a final database.
3) Delete: This property is used to generate delete command automatically,
if you have deleted some new row in the dataset or data table SQL
command builder automatically generate insert command and update a
final database.
4) Select: This property is used to generate the select command
automatically. It works in background. It is generated by using the SQL
command builder object.
Methods of Data Adapter:
1) Fill(): It is one of the most important method of data adapter. It is used to
fill the data into the data set or database for filling the data into data set in
data adapter you need to use the select command only.
2) Update(): It is used to update the changes make to dataset or data table
into the actual database table.
Events:
1) FillError():An error has occurred during a Fill operation.
2) RowUpdating():An UPDATE, INSERT, or DELETE operation on a row
(by a call to one of the Update methods) is about to begin.
DataSet Class :-
- ADO.NET caches data locally on the client and store that data into
dataset.
- The dataset is disconnected in memory representation of data. It is not
exact copy of database.
- It can be considered as local copy of the some portions of the database.
- The dataset contain a collection of one or more data table object made up
of rows and columns of data.
- Tables can be identifying in dataset using dataset’s tables property.
- It also contains primary key, foreign key, constraints and relation
information about the data in the data table object.
- Dataset are also fully XML feature whatever operations are made by user.
It is store temporary in the dataset when the use of this dataset is finished
changes can be made back to the control database for updating.
Properties of Dataset :
1) DataSetName: It allows you to set or get name of the database object.
2) HasErrors: It return a Boolean value to specify whether there are errors
while filling or updating.
3) Relation: It return a set of relations between tables loaded in the dataset.
4) Tables: It is the collection of all tables loaded in dataset object.
5) Tables.Count: It returns a values specifying how many tables are filled
into dataset.
6) Tables[0].TableName: It returns name of the first table loaded in dataset.
Instead of the table index you can also specify the name of the table.
7) Tables[0].Rows.Count: It gives total number of rows in the first table
loaded in the dataset.
8) Tables[0].Columns.Count: It gives total number of columns in the first
table loaded in the dataset.
9) Table[0].PrimaryKey: It gives all the primary key associate with first
table in the form of an array.
10) Tables[0].Constraints: It gives all the constrains associate with
particular table in form of constraints collection.
Methods of DataSet :
1) Clear(): It clears all the data inside the dataset.
2) WriteXML(): It allows you to create XML file from dataset data.
3) ReadXML(): It allows you to read XML file from and copy it into
dataset.
4) Tables[0].NewRow(): It allows you to create blank data row in the first
table of dataset collection.
5) Tables[0].Select(): It allows you to select group of data from first table
of dataset collection.
6) Tables[0].Rows.Add(): It also allows you to add a new data row for the
first table of data set collection.
7) Tables[0].Rows.Remove(): It also allows you to remove for first table of
dataset collection.
Display data on data bound Controls and Data Grid :-
- ASP.NET provides a wide variety of rich controls that can be bound to
data. Under the Data tab of the Visual Studio Toolbox, you can get
several controls under the Data tab that could be used to display data
from a data source, like a database or XML file.
- The standard ASP.NET data presentation controls are:
o DataList
o DetailsView
o FormView
o GridView
o ListView
o Repeater
Repeater Control :-
- The Repeater control was introduced with ASP.NET 1.0. The ASP.NET
Repeater is a basic container control that allows you to create custom lists
from any data available to the page.
- It provides a highly customized interface. It renders a read-only template;
in other words, it supports only the ItemTemplate to define custom
binding. The Repeater control is a Data Bind Control, also known as
container controls.
- The Repeater control is used to display a repeated list of items that are
bound to the control. This control may be bound to a database table, an
XML file, or another list of items. It has no built-in layout or styles, so
you must explicitly declare all layout, formatting and style tags within the
controls templates. You would require writing an explicit code to do
paging using this control. The Repeater repeats a layout of HTML you
write, it has the least functionality of the rest of the three controls.
- The Repeater control supports the following features:
o List format
o No default output
o More control and complexity
o Item as row
o no built-in selection capabilities
o no built-in support for edit, insert and delete capabilities
o no built-in support for paging, sorting and grouping capabilities
o no built-in layout or styles, need to declare all layout, formatting
and style tags explicitly within the control's templates
- The Repeater control allows you to create templates to define the layout
of its content.
Template Type :
1) ItemTemplate: Use this template for elements that are rendered once per
row of data.
2) AlternatingItemTemplate: Use this template for elements that are
rendered every other row of data. This allows you to alternate background
colors, for example.
3) HeaderTemplate: Use this template for elements that you want to render
once before your ItemTemplate section.
4) FooterTemplate: Use this template for elements that you want to render
once after your ItemTemplate section.
5) SeperatorTemplate: Use this template for elements to render between
each row, such as line breaks.
Grid View Control :-
- The GridView control is used to provide flexibility in working and
display data from the database. The data in the GridView control is
displayed in the tabular format. It has several properties assigned to the
control. Some of the properties are as mentioned below:
Property Description
It is a Boolean value indicating the control supports
AllowPaging
paging
It is a Boolean value indicating the control supports
AllowSorting
sorting
It accepts the current expression determining the
SortExpression
order of the row
It is used to get or set the data source object
Datasource
containing the data to populate the control
It is a Boolean value indicating that the user can edit
AutoGenerateEditButton
the record in the control
DataSourceID It indicates the data source control to be used
It is a Boolean value indicating that the user can
AutoGenerateDeleteButton
delete the record in the control
It is a Boolean value to indicate the columns are
AutoGenerateColumns automatically created for each field of the data
source
It is a Boolean value to indicate the column should
AutoGenerateSelectButton
be added to select the particular record
It gets the sorting direction of the column for the
SortDirection
control
It indicates the text to appear when there is no
EmptyDataText
record in the data source
Events:
Event Description
Occurs when one of the pager buttons is clicked, but
after the GridView control handles the paging
PageIndexChanged operation. This event is commonly used when you need
to perform a task after the user navigates to a different
page in the control.
Occurs when one of the pager buttons is clicked, but
before the GridView control handles the paging
PageIndexChanging
operation. This event is often used to cancel the paging
operation.
Occurs when a row's Cancel button is clicked, but
RowCancelingEdit before the GridView control exits edit mode. This
event is often used to stop the canceling operation.
Occurs when a button is clicked in the GridView
RowCommand control. This event is often used to perform a task when
a button is clicked in the control.
Occurs when a new row is created in the GridView
RowCreated control. This event is often used to modify the contents
of a row when the row is created.
Occurs when a data row is bound to data in the
RowDataBound GridView control. This event is often used to modify
the contents of a row when the row is bound to data.
Occurs when a row's Delete button is clicked, but after
RowDeleted the GridView control deletes the record from the data
source. This event is often used to check the results of
Event Description
the delete operation.
Occurs when a row's Delete button is clicked, but
before the GridView control deletes the record from the
RowDeleting
data source. This event is often used to cancel the
deleting operation.
Occurs when a row's Edit button is clicked, but before
RowEditing the GridView control enters edit mode. This event is
often used to cancel the editing operation.
Occurs when a row's Update button is clicked, but after
RowUpdated theGridView control updates the row. This event is
often used to check the results of the update operation.
Occurs when a row's Update button is clicked, but
RowUpdating before the GridView control updates the row. This
event is often used to cancel the updating operation.
Occurs when a row's Select button is clicked, but after
the GridView control handles the select operation. This
SelectedIndexChanged
event is often used to perform a task after a row is
selected in the control.
Occurs when a row's Select button is clicked, but
before the GridView control handles the select
SelectedIndexChanging
operation. This event is often used to cancel the
selection operation.
Occurs when the hyperlink to sort a column is clicked,
but after the GridView control handles the sort
Sorted
operation. This event is commonly used to perform a
task after the user clicks a hyperlink to sort a column.
Occurs when the hyperlink to sort a column is clicked,
but before the GridView control handles the sort
Sorting
operation. This event is often used to cancel the sorting
operation or to perform a custom sorting routine.
ListView Control :-
- The ListView control is used to bind to data items returned to the data
source and display them. The control displays data in a format defined by
using templates and styles. The list of templates supported by the control
are as shown below:
Templates Description
It identifies the data bound content to display for
ItemTemplate
single items
It identifies the content to be rendered between the
ItemSeperatorTemplate
items
It identifies the root template that defines the main
LayoutTemplate
layout
GroupTemplate It identifies the content of the group layout
It identifies the content to be rendered between the
GroupSeperatorTemplate
group of items
EmptyItemTemplate
It identifies the control to render for an empty item
when the GroupTemplate is used
It identifies the content to render if the data source
EmptyDataTemplate
returns no data
It identifies the content to render for the selected data
SelectedItemTemplate item to differentiate the selected item from the other
displayed items
EditItemTemplate It identifies the content to render when the item is lost
It identifies the content to render when an item is
InsertItemTemplate
being inserted
DataList Control :-
- The DataList control is used to display a repeated list of items that are
bound to the control. There are different templates using which user can
design the layout of the control. The template property are mentioned
below:
1. Connection – To work with the data in a database, the first obvious step
is the connection. The connection to a database normally consists of the
below-mentioned parameters.
1. Database name or Data Source – The first important parameter is
the database name. Each connection can only work with one
database at a time.
2. Credentials – The next important aspect is the 'username' and
'password'. This is used to establish a connection to the database.
3. Optional parameters - You can specify optional parameters on
how .net should handle the connection to the database. For
example, one can specify a parameter for how long the connection
should stay active.
2. Selecting data from the database – Once the connection is established,
data is fetched from the database. ASP.Net has the ability to execute 'sql'
select command against the database. The 'sql' statement can be used to
fetch data from a specific table in the database.
3. Inserting data into the database – ASP.Net is used to insert records into
the database. Values for each row that needs to be inserted in the database
are specified in ASP.Net.
4. Updating data into the database – ASP.Net can also be used to update
existing records into the database. New values can be specified in
ASP.Net for each row that needs to be updated into the database.
5. Deleting data from a database – ASP.Net can also be used to delete
records from the database. The code is written to delete a particular row
from the database.
Step :
(1) Create a web site and add a SqlDataSourceControl on the web form.
(4) Once the connection is set up, you may save it for further use. At the
next step, you are asked to configure the select statement:
(5) Select the columns and click next to complete the steps. Observe the
WHERE, ORDER BY, and the Advanced buttons. These buttons allow
you to provide the where clause, order by clause, and specify the insert,
update, and delete commands of SQL respectively. This way, you can
manipulate the data.
(6) Add a GridView control on the form. Choose the data source and
format the control using AutoFormat option.
(7) After this the formatted GridView control displays the column
headings, and the application is ready to execute.
// DataGridExample.aspx
using System;
using System.Data;
using System.Data.SqlClient;
namespace AdoNetExample
{
public partial class DataGridExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("data source=.; database=
student; integrated security=SSPI"))
{
SqlDataAdapter sde = new SqlDataAdapter("Select * from student", co
n);
DataSet ds = new DataSet();
sde.Fill(ds);
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
}
}
}
}
Binding Standard web server control :-
- ASP.NET allows powerful feature of data binding, you can bind any
server control to simple properties, collections, expressions and/or
methods. When you use data binding, you have more flexibility when you
use data from a database or other means.
- Data Bind controls are container controls.
- Data Binding is binding controls to data from databases. With data
binding we can bind a control to a particular column in a table from the
database or we can bind the whole table to the data grid.
- Data binding provides simple, convenient, and powerful way to create a
read/write link between the controls on a form and the data in their
application.
- Data binding allows you to take the results of properties, collection,
method calls, and database queries and integrate them with your
ASP.NET code. You can combine data binding with Web control
rendering to relieve much of the programming burden surrounding Web
control creation. You can also use data binding with ADO.NET and Web
controls to populate control contents from SQL select statements or
stored procedures.
- Data binding uses a special syntax: <%# %>
- The <%#, which instructs ASP.NET to evaluate the expression. The
difference between a data binding tags and a regular code insertion tags
<% and %> becomes apparent when the expression is evaluated.
Expressions within the data binding tags are evaluated only when the
DataBind method in the Page objects or Web control is called.
- Data Bind Control can display data in connected and disconnected model.
- Following are data bind controls in ASP.NET:
o Repeater Control
o DataGrid Control
o DataList Control
o GridView Control
o DetailsView
o FormView
o DropDownList
o ListBox
o RadioButtonList
o CheckBoxList
o BulletList
- Repeater Control, DataList Control and FormView Control are
unformatted controls.
- DetailsView and ForView controls display single tuple result at a time.
DropDownList, ListBox, RadioButtonList, CheckBoxList and BulletList
controls displays single column value
- There are three types of binding:
o Declarative Binding
o Static Binding
o Programmatically Binding
Display data on web form using Data bound controls :-
Language Integrated Query (LINQ) :-
- LINQ is known as Language Integrated Query and it is introduced in
.NET 3.5 and Visual Studio 2008. The beauty of LINQ is it provides the
ability to .NET languages(like C#, VB.NET, etc.) to generate queries to
retrieve data from the data source.
- For example, a program may get information from the student records or
accessing employee records, etc. In, past years, such type of data is stored
in a separate database from the application, and you need to learn
different types of query language to access such type of data like SQL,
XML, etc. And also you cannot create a query using C# language or any
other .NET language.
- To overcome such type of problems Microsoft developed LINQ. It
attaches one, more power to the C# or .NET languages to generate a
query for any LINQ compatible data source. And the best part is the
syntax used to create a query is the same no matter which type of data
source is used means the syntax of creating a query data in a relational
database is same as that used to create query data stored in an array there
is no need to use SQL or any other non-.NET language mechanism.
- You can also use LINQ with SQL, with XML files, with ADO.NET, with
web services, and with any other database.
- In C#, LINQ is present in System.Linq namespace. It provides different
type of classes and methods which supports LINQ queries.
Architecture of LINQ :-
- The architecture of LINQ is 3-layered architecture. In which the topmost
layer contains language extension and the bottom layer contains data
sources.
- The main purpose behind creating LINQ is, before C# 3.0 we use for loop, foreach loop, or
delegates traverse a collection to find a specific object, but the disadvantage of using these
methods for finding an object is you need to write a large sum of code to find an object
which is more time-consuming and make your program less readable. So to overcome these
problems LINQ introduced. Which perform the same operation in a few numbers of lines
and make your code more readable and also you can use the same code in other programs.
- It also provides full type checking at compile time, it helps us to detect the error at the
runtime, so that we can easily remove them.
- With the help of LINQ you can easily work with any type of data source like XML, SQL,
Entities, objects, etc. A single query can work with any type of database no need to learn
different types of languages.
Advantages of LINQ :-
- User does not need to learn new query languages for a different type of
data source or data format.
- It increase the readability of the code.
- Query can be reused.
- It gives type checking of the object at compile time.
- It can be used with array or collections.
- LINQ supports filtering, sorting, ordering, grouping.