Getting Started
  Introduction
  What is ASP.NET?
  Language Support

ASP.NET Web Forms
  Introducing Web Forms
  Working with Server Controls
  Applying Styles to Controls
  Server Control Form Validation
  Web Forms User Controls
  Data Binding Server Controls
  Server-Side Data Access
  Data Access and Customization
  Working with Business Objects
  Authoring Custom Controls
  Web Forms Controls Reference
  Web Forms Syntax Reference

ASP.NET Web Services
  Introducing Web Services
  Writing a Simple Web Service
  Web Service Type Marshalling
  Using Data in Web Services
  Using Objects and Intrinsics
  The WebService Behavior
  HTML Pattern Matching

ASP.NET Web Applications
  Application Overview
  Using the Global.asax File
  Managing Application State
  HttpHandlers and Factories

Cache Services
  Caching Overview
  Page Output Caching
  Page Fragment Caching
  Page Data Caching

Configuration
  Configuration Overview
  Configuration File Format
  Retrieving Configuration

Deployment
  Deploying Applications
  Using the Process Model
  Handling Errors

Security
  Security Overview
  Authentication & Authorization
  Windows-based Authentication
  Forms-based Authentication
  Authorizing Users and Roles
  User Account Impersonation
  Security and WebServices

Localization
  Internationalization Overview
  Setting Culture and Encoding
  Localizing ASP.NET Applications
  Working with Resource Files

Tracing
  Tracing Overview
  Trace Logging to Page Output
  Application-level Trace Logging

Debugging
  The SDK Debugger

Performance
  Performance Overview
  Performance Tuning Tips
  Measuring Performance

ASP to ASP.NET Migration
  Migration Overview
  Syntax and Semantics
  Language Compatibility
  COM Interoperability
  Transactions

Sample Applications
  A Personalized Portal
  An E-Commerce Storefront
  A Class Browser Application
  IBuySpy.com

  Get URL for this page

Data Access and Customization


Introduction to Templated Controls

While the DataGrid server control demonstrated in the previous section is suitable for many Web application scenarios where a grid-like representation of data is appropriate, many times the presentation of data needs to be much richer. ASP.NET offers two controls, DataList and Repeater, that give you greater flexibility over the rendering of list-like data. These controls are template-based, and so have no default rendering of their own. The way data is rendered is completely determined by the your implementation of the control's templates, which describe how to present data items.

Like the DataGrid control, DataList and Repeater support a DataSource property, which can be set to any ICollection, IEnumerable, or IListSource type. The data in this DataSource is bound to the control using its DataBind method. Once the data is bound, the format of each data item is described by a template.

The ItemTemplate property controls the rendering of each item in the DataSource collection. Inside an ItemTemplate, you can define any arbitrary presentation code (HTML or otherwise). Using the ASP.NET data binding syntax, you can insert values from the data bound to the DataList or Repeater control, as shown in the following example.

<ASP:Repeater id="MyRepeater" runat="server">

    <ItemTemplate>
        Hello <%# DataBinder.Eval(Container.DataItem, "name") %> !
    </ItemTemplate>

</ASP:Repeater>

The Container represents the first control in the immediate hierarchy that supports the System.Web.UI.INamingContainer marker interface. In this case, the Container resolves to an object of type System.Web.UI.WebControls.RepeaterItem, which has a DataItem property. As the Repeater iterates over the DataSource collection, the DataItem contains the current item in this collection. For example, if the data source is set to an ArrayList of Employee objects, the DataItem is of type Employees. When bound to a DataView, the DataItem is of type DataRowView.

The following example demonstrates a Repeater control bound to a DataView (returned from a SQL query). HeaderTemplate and FooterTemplate have also been defined and render at the beginning and end of the list, respectively.

 
VB DataList1.aspx

[Run Sample] | [View Source]

The Repeater control just iterates over the bound data, rendering the ItemTemplate once for each item in the DataSource collection. It does not render anything besides the elements contained in its templates. While the Repeater is a general purpose iterator, the DataList provides some additional features for controlling the layout of the list. Unlike the Repeater, DataList renders additonal elements, like table rows and cells and spans containing style attributes, outside of the template definition to enable this richer formatting. For example, DataList supports RepeatColumns and RepeatDirection properties that specify whether data should be rendered in multiple columns, and in which direction (vertical or horizontal) the data items should be rendered. DataList also supports style attributes, as shown in the following example.

<ASP:DataList runat="server" DataSource="<%#MyData%>"
    RepeatColumns="2"
    RepeatDirection="Horizontal"
    ItemStyle-Font-Size="10pt"
    ItemStyle-Font-Name="Verdana"
>
    ...
</ASP:DataList>

Note: The remainder of this section concentrates on the many features of the DataList control. For more information about the Repeater control, refer to the Repeater topic in the Web Forms Controls Reference section of this tutorial.

The following sample demonstrates the use of the DataList control. Note that the look of the data items has been changed from the previous example, simply by changing the contents of the control's ItemTemplate property. The RepeatDirection and RepeatColumns properties determine how the ItemTemplates are laid out.

 
VB Datalist2.aspx

[Run Sample] | [View Source]

The following example further demonstrates the infinite flexibility of templates by changing the ItemTemplate yet again. This time, one of the DataItem values has been substituted for the "src" attribute of an <img> tag. The format String parameter of DataBinder.Eval has also been used to substitute a DataItem value in the query string for a URL.

 
VB Datalist3.aspx

[Run Sample] | [View Source]


Handling Postbacks from a Template

As in the DataGrid, you can fire a command from inside a DataList template that is passed to an event handler wired to the DataList itself. For example, a LinkButton inside the ItemTemplate might fire a Select command. By setting the OnSelectedIndexChanged property of the DataList, you can call an event handler in response to this command. The following example demonstrates this process.

The following sample demonstrates this code in action. In the MyDataList_Select event handler, you populate several other server controls with the details about the particular selected item.

 
VB Datalist4.aspx

[Run Sample] | [View Source]

Note that while the DataList recognizes a few special commands such as Select and Edit/Update/Cancel, the command string fired inside a template can be any arbitrary string. For all commands, the DataList's OnItemCommand is fired. You can wire this event to a handler as in the previous example; the following example shows how to do this.


<script runat="server">

    Protected Sub MyDataList_ItemCommand(Sender As Object, E As DataListCommandEventArgs)
        Dim Command As String = E.CommandName

        Select Case Command
            Case "Discuss"
                ShowDiscussions(E.Item.DataItem)
            Case "Ratings"
                ShowRatings(E.Item.DataItem)
        End Select
    End Sub

</script>

<ASP:DataList id="MyDataList" OnItemCommand="MyDataList_ItemCommand" runat="server">

    <ItemTemplate>

        <asp:linkbutton CommandName="Ratings" runat="server">
            View Ratings
        </asp:linkbutton>
        |
        <asp:linkbutton CommandName="Discuss" runat="server">
            View Discussions
        </asp:linkbutton>

    </ItemTemplate>

</ASP:DataList>
VB

Note that because more than one command can fire this event handler, you must employ a switch statement to determine the particular command that was fired. The following sample demonstrates this code in action.

 
VB Datalist5.aspx

[Run Sample] | [View Source]


Using Select and Edit Templates

In addition to handling the Select command using a page-level event handler, the DataList can respond to this event internally. If a SelectedItemTemplate is defined for the DataList, the DataList renders this template for the item that fired the Select command. The following example uses the SelectedItemTemplate to make the title of the selected book bold.

 
VB Datalist6.aspx

[Run Sample] | [View Source]

DataList also supports an EditItemTemplate for rendering an item whose index is equal to the DataList's EditItemIndex property. For details about how editing and updating works, refer to the Updating Data topic of the Data Access section of this tutorial.

 
VB Datalist7.aspx

[Run Sample] | [View Source]


Finding a Control Inside a Template

Sometimes it is necessary to locate a control contained inside a template. If a control is given an ID in a template, that control can be retrieved from its container (the first control in the parent hierarchy that supports INamingContainer). In this case, the container is the DataListItem control. Note that even though there are several controls with the same ID (by virtue of the DataList's repetition), each is contained logically in the namespace of the DataListItem container control.

You can go through the DataList's Items collection to retrieve the DataListItem for a given index, and then call the DataListItem's FindControl method (inherited from the base Control class) to retrieve a control with a particular ID.

VB

The following sample demonstrates this code in action.

 
VB Datalist8.aspx

[Run Sample] | [View Source]

Section Summary

  1. The DataList and Repeater controls provide developers fine-tuned control over the rendering of data-bound lists.
  2. Rendering of bound data is controlled using a template, such as the HeaderTemplate, FooterTemplate, or ItemTemplate.
  3. The Repeater control is a general-purpose iterator, and does not insert anything in its rendering that is not contained in a template.
  4. The DataList control offers more control over the layout and style of items, and outputs its own rendering code for formatting.
  5. The DataList supports the Select, Edit/Update/Cancel, and Item Command events, which can be handled at the page level by wiring event handlers to the DataList's Command events.
  6. DataList supports a SelectedItemTemplate and EditItemTemplate for control over the rendering of a selected or editable item.
  7. Controls can be programmatically retrieved from a template using the Control.FindControl method. This should be called on a DataListItem retrieved from the DataList's Items collection.


Copyright 2001 Microsoft Corporation. All rights reserved.