ASP.Net Data Binding

childlikenumberΑσφάλεια

4 Νοε 2013 (πριν από 3 χρόνια και 7 μήνες)

59 εμφανίσεις

ASP.Net
Data Binding
IT 4203
Advanced Web Development
Jack G.
Zheng
Fall 2010
Data Binding Overview

Data binding is a flexible association between
Web UI controls and data sources, managed by
the
.Net
framework.

Dynamic Controls = Controls + Data
Sources

Two ways to add data to controls:
2
ASP.Net
Web
Controls
Data Source
Objects:
Collections
ADO.Net
,
DataSource
controls
Developer
Coding
Automatic
Data
Binding
3
Data Binding Controls

Simple data controls (
ListControl
based)

DropDownList

CheckBoxList
,
RadioButtonList

ListBox
,
BulletedList

Composite data controls

ListView

DataList

GridView

Repeater,
DetailsView
,
FormView
Data Sources

Generally, any class or component that implements
the
IList
interface is a valid data source.

Classes that support the
IList
interface in the .NET:

Collections

Array,
ArraList
, List<>,
HashTable
, Dictionary, etc.

ADO.Net

DataReader
,
DataSet
,
DataTable
,
DataView
,
DataColumn

DataSource
Controls

Linq
, Entity, Object, SQL Server, XML, etc.
4
Advantages and Disadvantages

Advantages

To write data driven applications quickly, with less
code and fast execution.

.NET automatically
generate data
binding
code
in the
background.

Control over the data binding process by using events.

Disadvantages

More optimized code can be written by using the
unbound or traditional methods.

Complete flexibility can only be achieved by using the
unbound approach.
5
General Binding Process
Step
List Controls
+ Binding
Code
Composite
Controls +
Binding Code
List Controls
+ Data Source
Controls
Composite
Controls
+ Data
Source
Controls
1. Preparing a
data source
Programmatically
get the data
source
object.
Declaratively configure
a data
source
control.
2. Defining a
web control
Define
control
styles
Define
control
styles, templates
and data binding
fields
Define
control
styles
Define
control
styles, templates
and data binding
fields
3. Linking
data
source to a
control
Programmatically set
the
control’s
DataSource
property (and other
relevant binding properties, such
as
DataMember
,
DataTextField
,
DataValueField
)
Declaratively s
et
the
control’s
DataSourceId
property
4. Binding
data
Programmatically call
the
DataBind
() method
(N/A)
6
Example:
DropDownList
+ Collection
protected void
Page_Load
(object sender,
EventArgs
e)
{
List<String> list = new List<string>();
list.Add
("Ford");
list.Add
("GM");
list.Add
("Chrysler");
this.DropDownList2.DataSource = list;
this.DropDownList2.DataBind();
this.RadioButtonList2.DataSource = list;
this.RadioButtonList2.DataBind();
}
7
Create a list collection of strings.
Set the control’s
DataSource
property to the collection object.
Call the
DataBind
method
The same data source can be
bound to multiple controls.
Example:
DropDownList
+
ADO.Net
DataReader
SqlConnection
con =
DBUtility.CreateDBConnection
();
SqlDataReader
source;
using (con)
{
con.Open
();
SqlCommand
cmd
= new
SqlCommand
();
cmd.CommandText
= "select distinct
CategoryName
from
PostCategories
";
cmd.Connection
= con;
source =
cmd.ExecuteReader
();
this.DropDownList1.DataSource = source;
this.DropDownList1.DataTextField = "
CategoryName
";
this.DropDownList1.DataValueField = "
CategoryName
";
this.DropDownList1.DataBind();
source.Close
();
}
8
Use a custom utility class to create
a database connection.
DataReader
can a data source.
DataTextField
is what’s being displayed
in the dropdown list;
DataValueField
is
the real value of a list item.
Column
names
Example:
List Controls +
ADO.Net
DataSet
DataSet
source =
this.GetADODS
();
this.DropDownList1.DataSource = source;
this.DropDownList1.DataMember = "
PostCategories
";
this.DropDownList1.DataTextField = "
SubCategoryName
";
this.DropDownList1.DataValueField = "
CategoryId
";
this.DropDownList1.DataBind();
this.RadioButtonList1.DataSource =
source.Tables
[0];
this.RadioButtonList1.DataTextField = "
SubCategoryName
";
this.RadioButtonList1.DataValueField = "
CategoryId
";
this.RadioButtonList1.DataBind();
this.BulletedList1.DataSource =
source.Tables
[0].
DefaultView
;
this.BulletedList1.DataTextField = "
SubCategoryName
";
this.BulletedList1.DataBind();
9
Use a method to load the
database data into a
DataSet
.
When a Dataset is the
data source; set the
DataMember
property
to a table in the
DataSet
DataTable
can be directly
set as a data source.
Column names.
DataView
can be used
as a data source.
Presenting Relational Data

Relational
data examples

Product
catalog, course list, event schedule, discussion threads, search
results, etc
.

Common relational (tabular) data presentation layouts and styles

Data table

http://www.atlanta
-
airport.com/Flights/search.aspx

Simple list

http://atlanta.craigslist.org/cta
/

Flow list

http://
jobsearch.monster.com/PowerSearch.aspx?tm=60

Grid

http://www.newegg.com/Store/Category.aspx?Category=19

Composite data controls can be used for all these layouts
10
Composite Data Controls

Composite data controls
are not directly transformed to a single
HTML element

Consist of different templates which is used to define layout and style
flexibly

More data fields can be bound to controls

Support bi
-
directional data
binding

Major composite data controls

Repeater: the simplest data control that repeats for each data item

DataList
: can repeat data items in a flexible layout and style

ListView
: the most powerful data control

GridView
: presents data in a table

More reference:

http://msdn.microsoft.com/en
-
us/library/system.web.ui.webcontrols.repeater(v=VS.90).aspx
11
Templates and Data
Binding Fields

Composite controls use templates to define its layout
and style. Common templates include:

ItemTemplate
: for each data item in the collection or table

AlternatingTemplate
: defined to
dinstinguising
odd and
even number data items

Data
binding fields
: to bind
a data field in templates;
the value of the data field (an expression) changes
for each item in the data source.

<%#
Eval
()
%>: output binding

<%#
Bind()
%>: bi
-
directional binding, usually used for user
input controls like textbox.
12
Example: Repeater Control
<
asp:Repeater
ID="Repeater1"
runat
="server">
<
HeaderTemplate
><h1>Books</h1></
HeaderTemplate
>
<
FooterTemplate
><h1>End</h1></
FooterTemplate
>
<
ItemTemplate
>
<%#
Container.ItemIndex+1 %>. <%#
Eval
("
BookTitle
") %>: <%#
Eval
(“
ListPrice
")
%>
</
ItemTemplate
>
<
AlternatingItemTemplate
>
-
<%#
Eval
("
BookTitle
") %>
</
AlternatingItemTemplate
>
<
SeparatorTemplate
><
br
/></
SeparatorTemplate
>
</
asp:Repeater
>

More reference

http
://
msdn.microsoft.com/en
-
us/library/x8f2zez5(v=VS.90
).
aspx

http://msdn.microsoft.com/en
-
us/library/system.web.ui.webcontrols.repeater(v=VS.90).
aspx
13
A
mixture of text, static HTML tags
and data binding fields in templates.
Templates
ItemTemplate
is the major template for data item output.
This template defines anything goes
between each data item output.
Don’t forget to set the
DataSource
property and call
the
DataBind
() method in the code
-
behind page.
Example: DataList Control
<
asp:DataList
ID="DataList1"
runat
="server" Width="900px"
CellPadding
="4"
RepeatColumns
="3"
RepeatDirection
="Horizontal"
ForeColor
="#333333">
<
ItemTemplate
>
<%#
Eval
("
BookTitle
") %><
br
/>
-
<%#
Eval
("ISBN") %><
br
/>
Publisher: <%#
Eval
("Publisher") %>
<h4>Price:$<%#
Eval
("
ListPrice
") %></h4>
</
ItemTemplate
>
<
ItemStyle
BackColor
="#E3EAEB" Width="300px"
VerticalAlign
="Top" />
<
AlternatingItemStyle
BackColor
="White" />
</
asp:DataList
>

More reference

http://msdn.microsoft.com/en
-
us/library/es4e4e0e(v=VS.90).
aspx

http://msdn.microsoft.com/en
-
us/library/system.web.ui.webcontrols.datalist(v=VS.90).
aspx
14
DataList
control can present data in
a grid or flow list layout. Use the

RepeatColumns
” and “Repeat
Direction” properties to set grid size.
Compared to Repeater,
DataList
provides style templates.
Don’t forget to set the
DataSource
property and call
the
DataBind
() method in the code
-
behind page.
Example:
ListView
<
asp:ListView
ID="ListView1"
runat
="server">
<
LayoutTemplate
>
<div runat="server" id="itemPlaceholder"
/><hr />
</
LayoutTemplate
>
<
ItemTemplate
>
<%#
Eval
("
BookTitle
") %><
br
/>
-
<%#
Eval
("ISBN") %><
br
/>
Publisher: <%#
Eval
("Publisher") %>
<h4>Price:$<%#
Eval
("
ListPrice
") %></h4>
</
ItemTemplate
>
</
asp:ListView
>

For more reference:

http://msdn.microsoft.com/en
-
us/library/bb398790(v=VS.90).aspx

http://msdn.microsoft.com/en
-
us/library/system.web.ui.webcontrols.listview(v=VS.90).aspx
15
Don’t forget to set the
DataSource
property and call
the
DataBind
() method in the code
-
behind page.
This template is required. Use a place
holder (div, span,
tr
, p, etc. with
runat
=“server”, id is required) to indicate
the content to be replaced by the content in
ItemTemplate
.
Example:
GridView
Control
<
asp:GridView
ID="GridView1"
runat
="server"
BackColor
="White"
BorderColor
="#DEDFDE"
BorderStyle
="None"
BorderWidth
="1px"
CellPadding
="4"
ForeColor
="Black"
GridLines
="Vertical">
<
AlternatingRowStyle
BackColor
="White"
/>
<
HeaderStyle
BackColor
="#6B696B" Font
-
Bold="True"
ForeColor
="White" />
<
RowStyle
BackColor
="#F7F7DE"
/>
</
asp:GridView
>

For more reference

http://msdn.microsoft.com/en
-
us/library/2s019wc0(v=VS.90).aspx

http://msdn.microsoft.com/en
-
us/library/system.web.ui.webcontrols.gridview(v=VS.90).aspx
16
Don’t forget to set the
DataSource
property and call
the
DataBind
() method in the code
-
behind page.
GridView
presents data in a table
layout, so it does not have flexible
layout templates. Style templates can
be defined.
Composite Controls Comparison
17
Functionalities
Control
Type
Flexible
Layout
Data
Grouping
Sorting
Paging
Update
and Delete
Insert
ListView
supported
supported
supported
supported
supported
supported
GridView
X
X
supported
supported
supported
X
DataList
supported
supported
X
X
X
X
Repeater
supported
X
X
X
X
X
Data Source Control

Data source control is a declarative way to define a data
source in the .
aspx
page and make it available for other
controls to bind to, without requiring code.

They can connect to and retrieve data from a data source

They can also support modifying data.

For more information

http://msdn.microsoft.com/en
-
us/library/ms227679(v=VS.90).
aspx
18
Major data
source control
Description
ObjectDataSource
To
work with a business object or other class and create Web
applications that rely on middle
-
tier objects to manage data.
Supports advanced sorting and paging scenarios unavailable with
the other data source controls.
SqlDataSource
Enables you to work with Microsoft SQL Server, OLE DB, ODBC, or
Oracle databases. When used with SQL Server, supports advanced
caching capabilities. The control also supports sorting, filtering, and
paging when data is returned as a
DataSet
object.
Example: Data Source Control
<form id="form1"
runat
="server
">
<
asp:SqlDataSource
ID="SqlDataSource1"
ProviderName
="
System.Data.SqlClient
"
SelectCommand
="SELECT top 12 * FROM [Books] WHERE ([
ListPrice
] <
@
ListPrice
)"
runat
="
server“
ConnectionString
="Data Source=basil.arvixe.com
; Initial
Catalog=it4203
-
classifieds;Persist
Security Info=True
; User ID=;Password=" >
<
SelectParameters
>
<
asp:Parameter
DefaultValue
="70" Name="
ListPrice
" Type="Decimal" />
</
SelectParameters
>
</
asp:SqlDataSource
>
<
asp:Repeater
ID="Repeater1"
DataSourceID
="SqlDataSource1"
runat
="server">
<
HeaderTemplate
><h3>Books</h3></
HeaderTemplate
>
<
ItemTemplate
>
<%#
Container.ItemIndex+1 %>. <%#
Eval
("
BookTitle
")%>: <%#
Eval
("
ListPrice
")
%>
</
ItemTemplate
>
<
SeparatorTemplate
><hr /></
SeparatorTemplate
>
</
asp:Repeater
>
</form>
19
Parameters can also be bound
to another control.
Data
-
bound control is the same, except
for adding the
DataSourceId
property.
Summary

Key concepts

Data binding

Data
-
bound
control

Data source

Data source control

Key skill

Bind collection type and
ADO.Net
type data sources to
simple list controls

Bind
ADO.Net
type data sources to composite data
controls

Understand the difference between the four composite
controls and be able to choose the appropriate one for
different purposes.
20
Key Resources

ASP.Net
Data Controls

http://msdn.microsoft.com/en
-
us/library/ms247243.aspx

ASP.Net
Data Source Controls

http://msdn.microsoft.com/en
-
us/library/ms247258(v=VS.90).aspx
21