820 likes | 971 Views
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
E N D
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
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
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
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()
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>
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>
Binding Data to the CheckBoxList and RadioButtonList Controls • RadioButtonList and CheckBoxList also are data-aware 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 two-dimensional 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>
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>
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
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: • 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: DimobjectNameAs NewOleDbConnection • 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: DimobjectNameAs NewOleDbDataAdaptor • 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: DimobjectNameAs NewOleDbCommand • 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/PrivateobjectNameAs NewDataSet • 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/PrivateobjectNameAs 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