Transcript Chapter 7
Data-Aware Controls in
®
ASP.NET Applications
ASP.NET
Data Binding Techniques
• A data source represents data
– A simple hash table, an array, or a database (or any
other collection)
– Web controls are used to display the data
– Sometimes called Data controls because their
primary function is to display data
– Displayed in a simple list, drop-down list, or table
• Data binding is the process of assigning a data
source to a Web control
– Data can be bound to a variety of Web controls
Data Binding Techniques
SingleBind.aspx
Single-Expression Binding
(Page 1)
• Binds a single value or expression to a control/tag
• Enclosed within inline server tags, i.e.
(<% %>)
• Pound/digit symbol (#) before the expression name
– Expression is a call to some named procedure, either
programmer-defined or built-it (i.e. method or function)
– The return value is inserted into the control
• Example:
<asp:Image id="Logo" AlterateText="Logo"
ImageUrl="<%# GetImageURL %>"
runat="server" />
Single-Expression Binding
(Page 2)
• The server tag and expression may be entered into for
many property lines in the Properties window for
Web Server controls (not HTML controls)
• When the (DataBindings) property is selected, the
"DataBindings" dialog window is displayed
– Enter the server tag expression into the Custom
Binding Expression: window which names the
command to execute
• The radio button must be selected to enter an expression
• Call DataBind() method usually from Page_Load
event to bind the expression to each object
Assign Property Value Directly
Assign as a Data Binding
Key Entry into HTML View
Repeated-Expression Binding
(Page 1)
• Repeated expressions are bound to data controls
(controls that have a DataSource property)
– Could be a collection such as a HashTable, or an
ArrayList (i.e. Chapter 4)
– DataSet, DataTable, DataView, or DataReader from
a database also are repeated expressions
• CheckBoxList, RadioButtonList, DropDownList and
ListBox inherit from ListControls class and may have
data from any of the datasources above bound to them
Repeated-Expression Binding
(Page 2)
• Data sources also may to bound to the DataGrid
and DataList controls which are data controls that
inherit from class BaseDataList
• Repeater inherits from System.Web.UI.Controls
class directly
Repeated-Expression Binding
ASP.NET Data Objects
• DataSet
– A cached (off-line) set of records from a database
– Contains one or more DataTables
• DataTable and DataView
– Subset of rows of data from a DataSet
• DataReader
– Read-only, forward-only on-line stream of data
from a database
Data Binding Web Controls
• DropDownList—displays one value at a time using
the <select> tag; drops-down to display values
• ListBox—displays values in a box several lines at a
time using <select> tag
• RadioButtonList and CheckBoxList—groups
multiple controls
• Repeater—small, lightweight control that displays
data; repeats defined HTML content
• DataList—displays data from each data row in a list
• DataGrid—repeats content once for each data row;
places the data in a table of rows and columns
The DataSource Property
• For data-aware controls, names the set of data to be
displayed by the control
• Format:
controlName.DataSource =
arrayList/hashTable/DataSet/DataView
• Example:
ddProducts.DataSource = arrayList1
• If a HashTable is assigned to DataSource property:
– "Key" is the first element from the hash table
– "Value" is the second element from the hash table
The DataBind Method
• Binds one or more data-aware controls so that data is
linked to and displayed in the control
• Format:
Page/controlName.DataBind
– The Page object may be used to bind all objects when
there are more than one on the Web Form
• Examples:
ddProducts.DataBind()
Page.DataBind()
DataBind()
DropDownList.aspx
The DataTextFormatString Property
(Page 1)
• Provides formatting for elements in DataBound
controls
• Format string is in two parts, separated by a colon:
{"A:Bxx"}
– A specifies the index in a zero-based list of parameters
(always 0 because there is only one value per element)
– B specifies the format to display (C is currency, D is
decimal, F is fixed, etc.)
– xx specifies the number of decimal places to display
The DataTextFormatString Property
(Page 2)
• Example:
– {0:F2}
– Formats element to display a fixed point number with
two decimal places
– Advisable to always specify decimal positions to make
it easier for other programmers to read your code
Other Properties of Bound Controls
• DataTextField property—text displayed between or
associated with the tag block or element
• DataValueField property—used by the control as the
value attribute
Binding Data to DropDownList Control
• Creates an HTML <select> … </select> block with
<option> tags
• Sets the size attribute (height of the object) in the
HTML code sent to the browser as equal to 1
– The value 1 is the default for a dropdown list and will
not actually be specified in the HTML
• Example:
<asp:dropdownlist id="ddProducts"
runat="server"></asp:dropdownlist>
ListBox.aspx
Binding Data to a ListBox Control
• Creates an HTML <select> … </select> block with
<option> tags
• Sets the size attribute (height of the object) in the
HTML code sent to browser to a value greater than 1
• Example:
<asp:listbox id="lbProducts"
runat="server"></asp:listbox>
CheckBoxRadio.aspx
Binding Data to the CheckBoxList
and RadioButtonList Controls
• RadioButtonList and CheckBoxList also are dataaware controls
– Each item in series (of CheckBoxes or RadioButtons)
is created is an HTML <input> tag with the type
attribute equal either "checkbox" or "radio"
• Example:
<asp:checkboxlist id="MyCBL1"
runat="server"></asp:checkboxlist>
<asp:radiobuttonlist id="MyRBL1"
runat="server"></asp:radiobuttonlist>
Binding to a DataGrid Control
• Creates a grid of rows and columns to display twodimensional data arrays, i.e.
– It might display separate key and value items of a hash
table in two columns, each element in its own row
– Ideal for displaying records and fields from a database
table, view or stored procedure
• Once the data set exists, set the DataSource property
of the DataGrid and call the DataBind() method
• Example:
<asp:DataGrid id="dgProducts"
runat="server"></asp:DataGrid>
DataGridSimple.aspx
The AutoGenerateColumns Property of
the DataGrid Control
• Specifies whether of not columns in the grid are
automatically created from the DataSource when the
page loads
– By default all columns are displayed in a DataGrid
since the AutoGenerateColumns properties is set to
True
– If set to False, the <Columns> … </Columns> block
must be used with <asp:BoundColumns> tags to name
fields to display from DataSource
• Required when using a HashTable since DataGrid does
not have DataTextField and DataValueField properties
The <Column> Control
• When configuring a data source (i.e. HashTable,
DataSet, DataView) programmatically, the DataGrid
columns are not created until the code executes
• The <Columns> … </Columns> control block can be
added manually to the HTML view to build columns
• Format:
<Columns>
columnElements
</Columns>
The <asp:BoundColumn> Control
(Page 1)
• Displays only selected items from data source in the
columns of a DataGrid or other object
• One or more controls are embedded in the <Columns>
… </Columns> block
• Properties:
– DataField—names field for display from data source
– HeaderText—text displayed at top of column
– DataFormatString—uses the same format syntax as
the DataTextFormatString
The <asp:BoundColumn> Control
(Page 2)
• Example:
<Columns>
<asp:BoundColumn DataField="Value"
HeaderText="Price"
DataFormatString="{0:C}">
</asp:BoundColumn>
<asp:BoundColumn …
</Columns>
Setting DataGrid Formatting
• Found in the Properties window, separate formatting
is available for:
– HeaderStyle
– ItemStyle
– FooterStyle
• Also may be keyed manually in the HTML view
– Be careful to not enter the <ItemStyle> tag inside a
<Column> … </Column> block
• Such an error would cause the style of just that one
column to be formatted
Binding to a DataList Control
• Used to create a simple, one-dimensional list
• An <ItemTemplate> control is required in DataList to
identify the columns to display and to format data
– Like a loop that formats every line in the DataList or
other object
– Templates are used to store data binding instructions
• Example:
<asp:DataList id="dlProducts" runat="server">
ItemTemplateInformation
</asp:DataList>
DataList.aspx
Templates
(Page 1)
• Templates
– Binds data to individual areas within the control
providing the ability to format the control
– Combines content, HTML, styles, return values of
methods and formatting elements into a single column
• May be used in a DataGrid to create an HTML stream
of characters
• An ItemTemplate is required for the DataList and
Repeater controls
– Information will be displayed one time for each
row/element in the DataSource, like a loop)
Templates
(Page 2)
• Types:
– HeaderTemplate—modifies content and appearance
of data in header section (first row)
– ItemTemplate—configures data rows; <img> and
many other HTML elements may be included as well
as data source items
– FooterTemplate—configures data in footer section
(last row)
– SeparatorTemplate—configures elements that appear
between each of the items
– EditItemTemplate—modifies configuration of
columns or rows that currently are being edited
Templates
(Page 3)
• Example:
<asp:DataList id="dlProducts" runat="server">
<ItemTemplate>
<b><%# Container.DataItem.Value %></b>
: <%# Container.DataItem.Key %><br>
</ItemTemplate>
</asp:DataList>
The Container.DataItem Function
• A server expression used in a template to identify
the columns to bind to a control
• Retrieves and stores values, and places them into
the HTML output stream
• Format:
Container.DataItem("fieldNameString")
• Examples:
<%# Container.DataItem("ProductId") %>
<%# Container.DataItem.Key %>
– In the second example, the key (first) element from
a hash table is the bound data item
The DataBinder.Eval Function
• A server expression used in a template that, in a
single statement, identifies the columns to bind to
control along with the formatting instructions
• Like Container.DataItem function, retrieves values
and places them into the HTML output stream
• Format for data-aware controls:
DataBinder.Eval(Container.DataItem,
"fieldName", "dataFormatString")
• Example:
<%# DataBinder.Eval(Container.DataItem,
"Value", "{0:C}") %>
Binding Data to a Repeater Control
(Page 1)
• Used to create tables, comma-delimited lists, bulleted
lists, and numbered lists
• Has no default appearance so it must be configured in
HTML view
• Data can be inserted with:
– An HTML <table> tag
– ASP.NET templates include header, footer, alternating,
item and separator templates
• To position a Repeater control, use the HTML <div>
tag or an ASP.NET Panel control
Repeater.aspx
Binding Data to a Repeater Control
(Page 2)
• Example:
<asp:Repeater id="Repeater1" runat="server">
ItemTemplateInformation
</asp:Repeater>
The ADO Objects
•
There are five (5) objects that must be declared:
1.
2.
3.
4.
5.
Connection (OleDbConnection)
DataAdaptor (OleDbDataAdaptor)
Command (OleDbCommand)
DataSet
DataTable or DataView
The OleDbConnection Object
• A programmer-defined identifier which defines the
connection to a database file
• Stores connection information (ConnectionString
property) including the DBMS type, as well as the
path and filename of database
• Format:
Dim objectName As New OleDbConnection
• Example:
Dim conTaraStore As New OleDbConnection
– Prefix for OleDbConnection objects is "con"
The OleDbDataAdaptor Object
• A programmer-defined identifier (in this case a
reference variable/object)
• Performs the operations required to communicate
between an ASP.NET application and a database file
• Format:
Dim objectName As New OleDbDataAdaptor
• Example:
Dim daProducts As New OleDbDataAdaptor
– Prefix for OleDbDataAdaptor objects is "da"
The OleDbCommand Object
• A programmer-defined identifier which stores the
SQL command information that must execute to
establish the database connectivity
• Stores a command (CommandText property) that
may returns specific records
– Or store commands to insert, update or delete rows
• Format:
Dim objectName As New OleDbCommand
• Example:
Dim cmdProducts As New OleDbCommand
– Prefix for OleDbCommand objects is "cmd"
The DataSet Object
• Programmer-defined identifier (reference variable)
which stores the collection of tables …
– The object may store more than one table
returned by the OleDbDataAdaptor object
• Tables literally are stored off-line in RAM
• Format:
Dim/Private objectName As New DataSet
• Example:
Dim dsProducts As New DataSet
– Prefix for DataSet objects is "ds"
The DataTable Object
(Page 1)
• Programmer-defined identifier which stores a
reference to a single table from a DataSet that is
stored in RAM
• The data then is manipulated off-line
– The physical database on disk may be updated after
the processing of the data is completed
• The DataTable object points to one of the tables
from the DataSet object
The DataTable Object
(Page 2)
• Format:
Dim/Private objectName As DataTable
• Example:
Dim dtProducts As DataTable
– The reserved word New is not used because the object
variable is a pointer (points to an address in RAM)
– Prefix for DataTable objects is "dt"
Importing a Namespace
(Page 1)
• Use of the keyword Imports lets developer reference
a namespace element from the .NET framework
without fully qualifying the element
• Statement must appear at the top of a module before
the class header ("Public Class … ") usually after the
Option Explicit and Option Strict statements
Importing a Namespace
•
(Page 2)
Format:
Imports Namespace.Namespace.etc.
•
If "OleDbConnection" class is in System.Data.OleDb
namespace the following Imports statement lets the
class be called directly:
Imports System.Data.OleDb
…
Dim conTaraStore As New OleDbConnection
•
Instead of:
Dim conTaraStore as New
System.Data.OleDb.OleDbConnection
Linking the Objects
•
(Page 1)
There are six (6) steps necessary to create the links
between the objects and access the database:
Assign a string to the ConnectionString property of
the OleDbConnection object:
2. Assign a SQL string to the CommandText property
of the OleDbCommand object
3. Assign the Connection object as the Connection
property of the Command object
4. Assign Command object as the SelectCommand
property of the DataAdaptor object
1.
Linking the Objects
•
(Page 2)
The six (6) steps necessary to create links between
the objects and access the database (con.):
5.
6.
Call the Fill method of the DataAdaptor object with
the DataSet object as its argument
Assign the Tables property of the DataSet object to
the DataTable object with the first returned table
The ConnectionString Property
(Page 1)
• For the OleDbConnection object, builds a String
which establishes the filename and other connection
arguments to the data source
• The information items is in the form of key=value
pairs each separated by a semicolon (;)
• The Provider string specifies the DBMS type, i.e.
"Provider=Microsoft.Jet.OLEDB.4.0"
• The Source string specifies path (location) to the
database and its filename, i.e.
"Data Source=c:\TaraStore.mdb"
The ConnectionString Property
(Page 2)
• Format:
ConnectionObjectName.ConnectionString =
"ProviderString;SourceString"
• Example:
mconPayables.ConnectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=c:\TaraStore.mdb"
The CommandText Property
• For the OleDbCommand object, a String that defines
the SQL SELECT, INSERT, UPDATE, or DELETE
command
• Format:
CommandObjectName.CommandText =
"SQLCommandString"/StringVariable
• Example:
pcmdVendor.CommandText = "SELECT * FROM
Products"
The Connection Property
• For the OleDbCommand object, stores information
about the DBMS to which the command references
• Effectively creates the link between the Command
object and the Connection object
• Format:
CommandObjectName.Connection =
ConnectionObjectName
• Example:
cmdProducts.Connection = conTaraStore
The SelectCommand Property
• For the OleDbDataAdaptor object, stores SQL
SELECT command information to be executed by
the DBMS
• Effectively creates a link between the DataAdaptor
object and the Command object
• Format:
DataAdaptorObjectName.SelectCommand =
CommandObjectName
• Example:
daProducts.SelectCommand = cmdProducts
The Fill Method
• A method of OleDbDataAdapter objects which:
– Opens the connection to the data provider (DBMS)
– Sends the SQL SELECT command
– After the data provider executes the command,
populates DataSet with table data from database
• Format:
DataAdapterObjectName.Fill
(DataSetObjectName)
• Example:
daProducts.Fill(dsProducts)
The Tables Collection
(Page 1)
• A member of the DataSet object representing the
one or more tables assigned to it
• A collection is an array of properties for an
individual object
• The Tables collection is the set of tables that is
stored in the DataSet object and may include one or
more tables
The Tables Collection
(Page 2)
• Format:
DataSetObjectName.Tables(index)
• Example:
mdtVendor = mdsVendor.Tables(0)
– Here one table from the DataSet collection is assigned
to a DataTable object
– The index "0" is the first table from the DataSet
(points to a table)
TaraStore.mdb—The Products Table
DataGridDisplay.aspx
Modifying Data Columns in the
DataGrid Control
(Page 1)
• By default all columns are displayed in a DataGrid
since the AutoGenerateColumns properties is set to
True
• When configuring a data source (DataSet, DataTable,
or DataView) programmatically, the DataGrid
columns are not created until the code executes
Modifying Data Columns in the
DataGrid Control
(Page 2)
• The <Columns> … </Columns> control block can be
used to add columns manually to the HTML view
– Set DataField property for each <asp:BoundColumn>
to fieldname from the table
– Modify HeaderText property for each column to vary it
from default string which is fieldname
• Example:
<Columns>
<asp:BoundColumn DataField="CategoryName"
HeaderText="Name"></asp:BoundColumn>
<asp:BoundColumn …
</Columns>
TaraStore.mdb—The Categories Table
DisplayGridColumns.aspx
The <ItemStyle> Control
(Page 1)
• Columns have a header, footer, and item section
• When the <ItemStyle> control is embedded in an
<asp:BoundColumn>, developer may format that
column for every row in the table by setting properties
and values using IntelliSense
• Inserted into either:
– The <asp:DataGrid> … </asp:DataGrid> block format
all columns in all rows (but not headers and footers)
– The<asp:BoundColumn> … </asp:BoundColumn>
block to format individual columns
The <ItemStyle> Control
(Page 2)
• Example:
<asp:BoundColumn DataField="CategoryName"
HeaderText="Name">
<ItemStyle Font-Names="Trebuchet MS"
ForeColor="DarkSlateGray"></ItemStyle>
</asp:BoundColumn>
The Property Builder for the DataGrid
(Page 1)
• Style template controls (<HeaderStyle>, <ItemStyle>,
etc.) may be inserted into the HTML code for a
DataGrid using the Property Builder
• If data source configured programmatically, remember
to first create a <Column> … </Column> block with
<asp:BoundControl> controls in the HTML view
The Property Builder for the DataGrid
(Page 2)
• Right click on the DataGrid and select Property
Builder… from the shortcut menu
• Select the Columns tab to add columns to and/or
modify existing columns in the DataGrid control
– Modify each column’s HeaderText, DataField, and
other attributes here
– A <asp:BoundColumns> control should appear in the
Select columns: list for each column
The Property Builder for the DataGrid
(Page 3)
• Select the Format tab to modify the appearance of
template items, including:
– Header and Footer (top and bottom of grid), and Pager
(controls that link to previous and next pages in DataGrid)
– Items—adds formatting for rows within the
<asp:DataGrid> … </asp:DataGrid> block including
Normal (formats <ItemStyle> control for all columns)
– Columns—drill down clicking the plus (+) in each
column to reach its Header and Footer (for each column)
or Items (the cells) elements
• Select the column name to modify its width attribute
DisplayGridColumns.aspx—
Property Builder Properties (Page 1)
• Columns tab
– CategoryName—HeaderText:
– CategoryID—HeaderText:
"Name"
"Category ID"
DisplayGridColumns.aspx—
Property Builder Properties (Page 2)
• Format tab
– Header
• BackColor:
DarkSlateGrey
• Bold:
True
• Font name:
Trebuchet MS
• ForeColor:
White
• Horizontal alignment:
Center
– Items—Normal Items
• Font name:
Trebuchet MS
• Font size:
X-Small
– Columns—Columns(0)—Items
• Horizontal align: Center
Data Columns
• All of the following are column types that may be
inserted within a <Columns> … </Columns> block
to assign columns to a DataGrid:
– BoundColumn—binds the column to one field from a
data source
– TemplateColumn—customized columns; can be used
for formatting how entries appear both while both
displaying and editing data in a DataGrid control
– HyperLinkColumn—displays and creates a hyperlink
(may be configured in the Property Builder)
The HyperLinkColumn
• In place of NavigateURL, the following attributes may be
used to pass a query string to a called page
– DataNavigateUrlFormatString attribute—the format of a
URL with a query string that may store a variable value
– DataNavigateUrlField attribute—stores a value which can
be passed along with the key as part of the query string
• Example:
<asp:HyperLinkColumn
DataTextField="ModelName"
DataNavigateUrlField="ProductID"
DataNavigateUrlFormatString="Products.aspx
?ProductID={0}">
DataGridDetails.aspx
Column Styles
• These templates may be modified manually in the
HTML view, or by using the Property Builder
–
–
–
–
–
–
–
HeaderStyle—formats the HeaderTemplate
FooterStyle—formats the FooterTemplate
ItemStyle—formats individual columns in every row
AlternatingItemStyle—formats every other row
SelectedItemStyle—formats currently selected row
EditItemStyle—formats the row in edit mode
PagerStyle—formats the page navigation controls
• PageSize—stores the number of rows number displayed
RepeaterTemplate.aspx
Additional Properties for the DataList
Control
• RepeatColumns property—an integer which specifies
the number of columns that may be displayed in the
DataList for each of the <ItemTemplate> elements
• RepeatDirections property—direction of repetition
for the RepeatColumns property in <ItemTemplate>
columns within the grid
– RepeatDirection.Horizontal
– RepeatDirection.Vertical
DataListTemplate.aspx