ASP.net Unit -III
ASP.net Unit -III
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:
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.
ObjectDataSource It allows binding to a custom .Net business object that returns data.
The DataSourceView class serves as the base class for all data source view classes, which define
the capabilities of data source controls.
Properties Description
CanUpdate Indicates whether updates are allowed on the underlying data source.
Events Gets a list of event-handler delegates for the data source view.
Methods Description
The following code snippet provides the basic syntax of the control:
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:
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:
Explore our latest online courses and learn new skills at your own pace. Enroll and become a
certified exert to boost your career.
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.
public Student()
{}
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:
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:
Run the project, it retrieves the hard coded tuples from the students class.
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
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
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).
When the application is executed, check that the entire title column is bound to the bulleted list and
displayed.
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.
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;
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;
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:
<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>
<tr>
<td style="width: 228px; height: 21px">
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>
</div>
</form>
Step (3) : Finally, write the following code behind routines of the application:
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();
}
}
return allbooks;
}
All classes belongs to ADO.NET are defined and arrange in “System.Data” namespace.
The architecture of ADO.NET is following.
User Instance=true"/>
</connectionStrings>
using System.Configuration;
After then we declare a string variable to store connection string that getting from
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:
Connection Class:
This namespace support following Connection Class to establishing
connection.
SqlConnection
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
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
records.
Working process with DataReader Class:( for MS-SQL Server database)
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.
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)
Here
N.MANIMOZHI-AP/ DEPARTMENT OF COMPUTER APPLICATION- RASC
Page 24
22UCSCC62 : DOTNET PROGRAMMING
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;