2. INTRODUCTION TO DATA BINDING
Almost every web application has to deal with data,
whether it’s stored in a database, an XML file, a structured
file, or something else.
Retrieving this data is only part of the challenge—a
modern application also needs a convenient, flexible, and
attractive way to display the data in a web page.
ASP.NET includes a rich and full-featured model for
data binding.
Data binding allows you to bind the data objects you’ve
retrieved to one or more web controls, which will then show
the data automatically.
Don’t need to write time-consuming logic to loop through
2
rows, read multiple fields, and manipulate individual
3. Introduction to Data Binding cont..
Tomake your life even easier, use
ASP.NET’s data source controls.
A data source control allows you to
define a declarative link between your
page and a data source.
Configure a data source control, and
hook it up to your web controls at design
time, and ASP.NET will take care of all the
data binding details.
3
4. Basic Data Binding
Data binding is a feature that allows you to
associate a data source with a control and have that
control automatically display your data.
Key characteristic is that it’s declarative.
Most web controls (including TextBox, LinkButton,
Image, and many more) support single-value data
binding.
To use single-value binding, create data binding
expressions.
Many web controls support repeated-value binding.
Assign DataSource property of the control to data 4
5. Single-Value Binding
The controls that support single-value data binding allow you to
bind some of their properties to a data binding
expression.
The expression is entered in the .aspx markup portion of the
page,
not in code behind file.
Here’s an example:
<%# expression_goes_here %>
For example, if you have variable in your page class named
EmployeeName, you could write the following:
<%# EmployeeName %>
To evaluate a data binding expression such as this, call the
Page.DataBind() method.
The following data binding expressions are all valid:
<%# GetUserName() %>
<%# "John " + "Smith" %> 5
6. Other Types of Expressions
ASP.NET also has support for a different type of expression,
commonly known as $ expressions.
$ expression is a code sequence in an .aspx page and will be
evaluated by an expression builder when the page is rendered.
ASP.NET includes a built-in expression builder that allows to
extract custom application settings and connection string information
from the web.config file.
For example, if you want to retrieve an application setting named
appName from the <appSettings>
<asp:Literal Runat="server" Text="<%$ AppSettings:appName
%>" />
Here’s an example that uses the
ConnectionStringsExpressionBuilder:
<asp:Literal Runat="server" Text="<%$ ConnectionStrings:Northwind 6
7. Repeated-Value Binding
Repeated-value binding allows you to bind an
entire list of information to a control.
Could be a collection of custom objects (for
example, in an ordinary ArrayList or Hashtable) or a
collection of rows (for example, with a DataReader or
DataSet).
Important properties of repeated controls:
DataSource
DataSourceID
DataTextField
7
DataTextFormatString
8. Binding to a DataReader
Can bind any data structure that implements the
ICollection interface or one of its derivatives.
The following list summarizes many of these data
classes
All in-memory collection classes, such as
Collection, ArrayList, Hashtable, and Dictionary.
An ADO.NET DataReader object, which provides
connection-based, forward-only, and read-only
access to the database
The ADO.NET DataView, which provides a view
onto a single disconnected DataTable object.
Any other custom object that implements the
8
9. The Rich Data Controls
In addition to the simple list controls, ASP.NET
includes some rich data controls that support repeated-
value binding.
Rich Controls are designed exclusively for data
binding.
Support higher-level features such as editing and other
features.
The rich data controls include the following:
GridView : The GridView is an all-purpose grid
control for showing large tables of
information
DetailsView: Shows a single record at a time, in a
table that has one row per field 9
FormView: FormView shows a single record at a
10. The Rich Data Controls cont..
GridView provides a DataSource property for the data
object.
DataBind() method triggers to read the data object and
display each record.
GridView automatically generates a column for every
property or every field.
For Example:
<asp:GridView ID="grid" runat="server"
AutoGenerateColumns="true" />
Now, define a query that selects several fields from the
Employees
string sql = "SELECT EmployeeID, FirstName,
LastName, Title, City " +
"FROM Employees";
Bind the GridView to a DataReader . 10
grid.DataSource = reader;
11. Data Source Controls
To access database data access code is needed.
With data source controls, you can avoid writing any data
access code.
The data source controls include any control that
implements the IDataSource interface.
The .NET Framework includes the following data source
controls:
Data Source Control Description
SqlDataSource Allows you to connect to any data source that has an
ADO.NET data provider. Includes SQL Server, Oracle,
and the OLE DB or ODBC data sources.
ObjectDataSource Allows you to connect to a custom data access class.
AccessDataSource Allows you to read and write the data in an Access
database file (.mdb).
XmlDataSource allows you to connect to an XML file
SiteMapDataSource allows you to connect to the Web.sitemap file that 11
describes the navigational structure of your website
12. The SqlDataSource
Data source controls turn up in the .aspx markup
portion of your web page like ordinary controls.
Here’s an example:
<asp:SqlDataSource ID="SqlDataSource1"
runat="server" ... />
The SqlDataSource represents a database
connection that uses an ADO.NET provider.
.NET ships with these four provider factories
System.Data.SqlClient
System.Data.OracleClient
System.Data.OleDb
System.Data.Odbc 12
13. The SqlDataSource cont..
The next step is to supply the required connection string.
For example
<configuration>
<connectionStrings>
<add name="Northwind“ connectionString="Data
Source=localhost;Initial Catalog=Northwind;Integrated
Security=SSPI"/>
</connectionStrings>
...
</configuration>
Specify it in the SqlDataSource using a $ expression.
<asp:SqlDataSource ConnectionString=
"<%$ ConnectionStrings:Northwind %>" ... />
13
14. Selecting Records
Each SqlDataSource control allows you to retrieve a single
query.
Can add corresponding commands for deleting, inserting, and
updating rows.
The SqlDataSource command logic is supplied through four
properties:
SelectCommand,
InsertCommand,
UpdateCommand, and
DeleteCommand
Example:
<asp:SqlDataSource ID="sourceEmployees" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:Northwind
14
%>" SelectCommand="SELECT EmployeeID, FirstName,
15. Selecting Records cont..
Clearly, the great advantage of the data source
controls is that they allow you to configure data binding
at design time, without writing tedious code.
Controls can be bound to a DataReader or a
DataView
Which approach does the SqlDataSource control
use?
DataSourceMode to SqlDataSourceMode.DataSet
(the default) or to SqlDataSourceMode.DataReader.
The DataSet mode is almost always better, because
it supports advanced sorting, filtering, and caching 15
16. Parameterized Commands
Can we pass parameters to SqlDataSourceMode???
<asp:SqlDataSource ID="sourceEmployees"
runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$
ConnectionStrings:Northwind %>"
SelectCommand="SELECT EmployeeID, FirstName,
LastName,Title, City FROM Employees WHERE
City=@City">
<SelectParameters>
<asp:ControlParameter ControlID="lstCities"
Name="City"
PropertyName="SelectedValue" /> 16
</SelectParameters>
17. Stored Procedures
Can we use stored procedure with SqlDataSource
control???
<asp:SqlDataSource ID="sourceEmployees"
runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$
ConnectionStrings:Northwind %>"
SelectCommand="GetEmployeesByCity"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="lstCities"
Name="City"
PropertyName="SelectedValue" /> 17
</SelectParameters>
18. More Parameter Types
Parameter values aren’t necessarily drawn from other
controls.
Can map a parameter to any of the parameter types defined
in table below Control Tag
Source Description
Control property <asp:ControlParameter> A property from another control on
the page.
Query string <asp:QueryStringParamete A value from the current query
value r> string.
Session state <asp:SessionParameter> A value stored in the current user’s
value session.
Cookie value <asp:CookieParameter> A value from any cookie attached to
the
current request.
Profile value <asp:ProfileParameter> A value from the current user’s
profile
A form variable <asp:FormParameter> A value posted to the page from an
input control. 18
19. More Parameter Types cont..
Don’t need to remember the different tag names
Visual Studio provides a handy editor that lets you
create your command and define your parameters.
19
20. Updating Records
ASP.NET’s rich data controls—including the GridView,
DetailsView, and FormView—all have editing features
First step is to define suitable commands for the operations
(like InsertCommand, DeleteCommand, and UpdateCommand)
Example
<asp:SqlDataSource ID="sourceEmployees"
runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:Northwind
%>"
SelectCommand="SELECT EmployeeID, FirstName,
LastName, Title, City FROM Employees"
UpdateCommand="UPDATE Employees SET
FirstName=@FirstName,
LastName=@LastName,Title=@Title, City=@City FROM
Employees WHERE EmployeeID=@EmployeeID">
To enable editing, set the GridView.AutoGenerateEditButton property 20
to true.
21. Updating Records
Can use stored procedures to update the records
Example
<asp:SqlDataSource ID="sourceEmployees" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:Northwind
%>" SelectCommand="SELECT EmployeeID, FirstName,
LastName, TitleOfCourtesy FROM Employees"
UpdateCommand="UpdateEmployee"
UpdateCommandType="StoredProcedure"
OnUpdating="sourceEmployees_Updating" >
<UpdateParameters>
<asp:Parameter Name="First" Type="String"
/>
<asp:Parameter Name="Last" Type="String"
/> 21
</UpdateParameters>
22. Deleting Records
Deletinga record is similar to updating it.
Create a DeleteCommand that removes the record
you want to delete.
Example
<asp:SqlDataSource ID="sourceEmployees"
runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$
ConnectionStrings:Northwind %>"
SelectCommand="SELECT EmployeeID,
FirstName, LastName, Title, City FROM
Employees" 22
DeleteCommand="DELETE Employees
23. Inserting Records
The GridView supports editing and deleting records, but it
doesn’t support insertion.
However, the DetailsView and FormView do support
insertion.
Example
<asp:SqlDataSource ID="sourceEmployees" runat="server"
ProviderName="System.Data.SqlClient"
ConnectionString="<%$ ConnectionStrings:Northwind
%>"
SelectCommand=
"SELECT EmployeeID, FirstName, LastName, Title,
City FROM Employees”
InsertCommand="INSERT INTO Employees
(FirstName,LastName,Title,City)
VALUES (@FirstName,@LastName,@Title,@City)"> 23
24. Disadvantages of the SqlDataSource
Data access logic embedded in the page.
Maintenance in large applications.
Lack of flexibility.
Inapplicability to other data tasks.
24