Você está na página 1de 21


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:

Developer Coding ASP.Net Web Controls Automatic Data Binding
Data Source Objects: Collections ADO.Net, DataSource controls

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:


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

DataReader, DataSet, DataTable, DataView, DataColumn


DataSource Controls

Linq, Entity, Object, SQL Server, XML, etc.

Advantages and Disadvantages


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.


More optimized code can be written by using the unbound or traditional methods. Complete flexibility can only be achieved by using the unbound approach.

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 controls DataSource property (and other relevant binding properties, such as DataMember, DataTextField, DataValueField) Programmatically call the DataBind() method

Declaratively set the controls DataSourceId property

4. Binding data


Example: DropDownList + Collection

protected void Page_Load(object sender, EventArgs e) {
List<String> list = new List<string>(); list.Add("Ford"); Create a list collection of strings. list.Add("GM"); Set the controls DataSource list.Add("Chrysler");
property to the collection object.

this.DropDownList2.DataSource = list; Call the DataBind method this.DropDownList2.DataBind(); this.RadioButtonList2.DataSource = list; this.RadioButtonList2.DataBind();

The same data source can be bound to multiple controls.


Example: DropDownList + ADO.Net DataReader

SqlConnection con = DBUtility.CreateDBConnection(); SqlDataReader source; Use a custom utility class to create a database connection. using (con) { con.Open(); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "select distinct CategoryName from PostCategories"; cmd.Connection = con; DataReader can a data source. source = cmd.ExecuteReader();
Column names this.DropDownList1.DataSource = source; this.DropDownList1.DataTextField = "CategoryName"; this.DropDownList1.DataValueField = "CategoryName"; this.DropDownList1.DataBind(); DataTextField is whats being displayed source.Close(); in the dropdown list; DataValueField is
the real value of a list item.

Example: List Controls + ADO.Net DataSet

DataSet source = this.GetADODS();
Use a method to load the database data into a DataSet.

this.DropDownList1.DataSource = source; this.DropDownList1.DataMember = "PostCategories"; this.DropDownList1.DataTextField = "SubCategoryName"; this.DropDownList1.DataValueField = "CategoryId"; this.DropDownList1.DataBind();

When a Dataset is the data source; set the DataMember property to a table in the DataSet

this.RadioButtonList1.DataSource = source.Tables[0]; this.RadioButtonList1.DataTextField = "SubCategoryName"; this.RadioButtonList1.DataValueField = "CategoryId"; Column names. this.RadioButtonList1.DataBind();

DataTable can be directly set as a data source.

this.BulletedList1.DataSource = source.Tables[0].DefaultView; this.BulletedList1.DataTextField = "SubCategoryName"; DataView can be used this.BulletedList1.DataBind(); 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 http://atlanta.craigslist.org/cta/ http://jobsearch.monster.com/PowerSearch.aspx?tm=60 http://www.newegg.com/Store/Category.aspx?Category=19

Simple list

Flow list


Composite data controls can be used for all these layouts


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:


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.

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> A mixture of text, static HTML tags and data binding fields in templates. <AlternatingItemTemplate> - <%# Eval("BookTitle") %> This template defines anything goes </AlternatingItemTemplate> between each data item output. <SeparatorTemplate><br /></SeparatorTemplate> </asp:Repeater> Dont forget to set the DataSource property and call the DataBind() method in the code-behind page. More reference

ItemTemplate is the major template for data item output.

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

Example: DataList Control

<asp:DataList ID="DataList1" runat="server" Width="900px" CellPadding="4" RepeatColumns="3" RepeatDirection="Horizontal" ForeColor="#333333"> DataList control can present data in <ItemTemplate> a grid or flow list layout. Use the <%# Eval("BookTitle") %><br /> RepeatColumns and Repeat -<%# Eval("ISBN") %><br /> Direction properties to set grid size. Publisher: <%# Eval("Publisher") %> <h4>Price:$<%# Eval("ListPrice") %></h4> </ItemTemplate> <ItemStyle BackColor="#E3EAEB" Width="300px" VerticalAlign="Top" /> <AlternatingItemStyle BackColor="White" /> Compared to Repeater, DataList
provides style templates.


More reference

Dont forget to set the DataSource property and call the DataBind() method in the code-behind page.

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

Example: ListView
<asp:ListView ID="ListView1" runat="server"> <LayoutTemplate> <div runat="server" id="itemPlaceholder" /><hr /> </LayoutTemplate> This template is required. Use a place <ItemTemplate> <%# Eval("BookTitle") %><br /> -<%# Eval("ISBN") %><br /> Publisher: <%# Eval("Publisher") %> <h4>Price:$<%# Eval("ListPrice") %></h4> </ItemTemplate>
holder (div, span, tr, p, etc. with runat=server, id is required) to indicate the content to be replaced by the content in ItemTemplate.


Dont forget to set the DataSource property and call the DataBind() method in the code-behind page.

For more reference:

http://msdn.microsoft.com/en-us/library/bb398790(v=VS.90).aspx http://msdn.microsoft.com/enus/library/system.web.ui.webcontrols.listview(v=VS.90).aspx


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" /> GridView presents data in a table layout, so it does not have flexible <RowStyle BackColor="#F7F7DE" />

layout templates. Style templates can be defined.


Dont forget to set the DataSource property and call the DataBind() method in the code-behind page.

For more reference

http://msdn.microsoft.com/en-us/library/2s019wc0(v=VS.90).aspx http://msdn.microsoft.com/enus/library/system.web.ui.webcontrols.gridview(v=VS.90).aspx

Composite Controls Comparison

Control Type ListView GridView DataList Flexible Layout Data Grouping Sorting Paging Update and Delete Insert

supported supported supported supported supported supported X X supported supported supported X X X X X X X X X

supported supported X

Repeater supported


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.

Major data source control

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.

For more information



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> Parameters can also be bound to another control. </asp:SqlDataSource> <asp:Repeater ID="Repeater1" DataSourceID="SqlDataSource1" runat="server"> <HeaderTemplate><h3>Books</h3></HeaderTemplate> Data-bound control is the same, except for adding the DataSourceId property. <ItemTemplate> <%# Container.ItemIndex+1 %>. <%# Eval("BookTitle")%>: <%# Eval("ListPrice") %> </ItemTemplate> <SeparatorTemplate><hr /></SeparatorTemplate> </asp:Repeater> </form>


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.

Key Resources

ASP.Net Data Controls


ASP.Net Data Source Controls