Recipe 2.4. Enhancing the Output of a Tabular Display


Problem

You need to display data from a database in a way that lets you organize and enhance the output beyond the confines of the DataGrid or GridView control's default tabular display. Selecting and editing the data are unimportant as is navigating through the data.

Solution

Use a Repeater control with templates and then bind the data to the control.

In the .aspx file, add a Repeater control and the associated templates for displaying the data.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Create a SqlDataSource.

  2. Set the ConnectionString, DataSourceMode, ProviderName, and SelectCommand properties of the SqlDataSource.

  3. Assign the data source to the Repeater control and bind it.

Figure 2-2 shows the appearance of a typical Repeater in a browser. Examples 2-4, 2-5 through 2-6 show the .aspx and code-behind files for an application that produces this result.

Figure 2-2. Using templates with Repeater control display output


Discussion

When your primary aim is to organize and enhance the output beyond the confines of the DataGrid and GridView control's default tabular display, the Repeater control is a good choice because, unlike a DataGrid or GridView, it has associated templates that allow you to use almost any HTML to format the displayed data. It has the advantage of being relatively lightweight and easy to use. When using Repeater, however, you should know about a handful of nuances that can make life easier and, in one instance, enhance performance.

Example 2-4 shows one of the most common approaches to using the Repeater control, which is to place the asp:Repeater element in a table and use its HeaderTemplate, ItemTemplate, and AlternatingItemTemplate attributes to format the displayed data as rows in the table.

A HeaderTemplate is used to define the header row of the table. In this example, the header is straight HTML with a single table row and three columns.

An ItemTemplate formats the even-numbered rows of data, and an AlternatingItemTemplate formats the odd-numbered rows. For both templates, a single row in the table is defined with the same three columns defined in the header template. In each of the three columns, data-binding statements (described later) define the data to be placed in each of the columns. The only differences between ItemTemplate and AlternatingItemTemplate are the stylesheet classes used to output the rows. If you do not need to output the data using alternating styles, omit the AlternatingItemTemplate attribute.

The data from the database is bound to the cells in the templates using the Eval method. The Title field is placed in the first column, the ISBN field is placed in the second column, and the Publisher field is placed in the third column:

 Eval("Title") Eval("ISBN") Eval("Publisher") <table width="90%" align="center" style="border-collapse:collapse;"> 

In Version 1.x, the data-bind statements had the following form:

 <%# DataBinder.Eval(Container.DataItem, <expression> %> 

In Version 2.0, the syntax has been simplified to the following form:

 <%# Eval(<expression>) %> 


If the header is pure HTML with no data binding required, removing the HeaderTemplate attribute and placing the header HTML before the asp:Repeater tag will be more efficient. By moving the header outside of the asp:Repeater tag, the creation of several server-side controls is eliminated, which reduces the time required to render the page and improves performance.


 <table width="90%" border="2" align="center" bordercolor="#000080" bgcolor="#FFFFE0" style="border-style:solid;border-collapse:collapse;"> <thead bgcolor="#000080" > <tr> <th align="center">Title</th> <th align="center">ISBN</th> <th align="center">Publisher</th> </tr> </thead> 

The Page_Load method in the code-behind, shown in Examples 2-5 (VB) and 2-6 (C#), creates a SqlDataSource, sets the properties to define the source of the data and the select command to retrieve the data from the database, and binds the data source to the GridView control.

See Also

Recipe 2.6 for another example of using a template with a tabular control

More About the Eval Method

Recipe 2.3 uses the Eval method to bind data from the database to cells in the templates, as in:

 <%#Eval("Title") %> 

The advantage of this approach is its simple syntax. However, because the Eval method uses late-bound reflection to parse and evaluate a data-binding expression (in this case, it's a simple string), there's a performance penalty associated with it.

 

<%#CType(Container.DataItem,DbDataRecord).Item("Title")%>

<%# ((DbDataRecord)Container.DataItem)["Title"] %>

For this syntax to work, explicit casting is required. When casting to DbDataRecord, add the following page-level directive to the beginning of your .aspx file:

 <%@ Import namespace="System.Data.Common" %> 


Example 2-4. Templates with Repeater control (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH02TemplatesWithRepeaterVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH02TemplatesWithRepeaterVB" Title="Templates with Repeater" %> <asp:Content  Runat="server" ContentPlaceHolder> <div align="center" > Templates With Repeater (VB) </div> <!-- Create a table within the cell to provide localized customization for the book list --> <table width="90%" align="center"      style="border-collapse:collapse;"> <asp:Repeater  Runat="server"> <HeaderTemplate> <thead > <tr> <th align="center"> Title</th> <th align="center"> ISBN</th> <th align="center"> Publisher</th> </tr> </thead> </HeaderTemplate> <ItemTemplate> <tr > <td> <%#Eval("Title")%> </td> <td align="center"> <%#Eval("ISBN")%> </td> <td align="center"> <%#Eval("Publisher")%> </td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr > <td> <%#Eval("Title")%> </td> <td align="center"> <%# Eval("ISBN") %> </td> <td align="center"> <%#Eval("Publisher")%> </td> </tr> </AlternatingItemTemplate> </asp:Repeater> </table> </asp:Content> 

Example 2-5. Templates with Repeater control code-behind (.vb)

 Option Explicit On Option Strict On Imports Microsoft.VisualBasic Imports System.Configuration Imports System.Data Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH02TemplatesWithRepeaterVB.aspx ''' </summary> Partial Class CH02TemplatesWithRepeaterVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load Dim dSource As SqlDataSource = Nothing If (Not Page.IsPostBack) Then 'configure the data source to get the data from the database dSource = New SqlDataSource() dSource.ConnectionString = ConfigurationManager. _ ConnectionStrings("dbConnectionString").ConnectionString dSource.DataSourceMode = SqlDataSourceMode.DataReader dSource.ProviderName = "System.Data.OleDb" dSource.SelectCommand = "SELECT Title, ISBN, Publisher " & _ "FROM Book " & _ "ORDER BY Title" 'set the source of the data for the repeater control and bind it repBooks.DataSource = dSource repBooks.DataBind() End If End Sub 'Page_Load End Class 'CH02TemplatesWithRepeaterVB End Namespace 

Example 2-6. Templates with Repeater control code-behind (.cs)

 using System; using System.Configuration; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH02TemplatesWithRepeaterCS.aspx /// </summary> public partial class CH02TemplatesWithRepeaterCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { SqlDataSource dSource = null; if (!Page.IsPostBack) { //configure the data source to get the data from the database dSource = new SqlDataSource(); dSource.ConnectionString = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dSource.DataSourceMode = SqlDataSourceMode.DataReader; dSource.ProviderName = "System.Data.OleDb"; dSource.SelectCommand = "SELECT Title, ISBN, Publisher " + "FROM Book " + "ORDER BY Title"; //set the source of the data for the repeater control and bind it repBooks.DataSource = dSource; repBooks.DataBind(); } } // Page_Load } // CH02TemplatesWithRepeaterCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net