Listing 94 Repeater Testaspx showing a more complicated view of the Customer table

Codebehind="RepeaterTest.aspx.cs" AutoEventWireup="false" Inherits="Chapter09_Template.WebForm1" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD>

<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">

<meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultCllentScrlpt" content="JavaScript (ECMAScrlpt)"> <meta name="vs_targetSchema" content="http://schemas.mlcrosoft.com/lntelllsense/leS"> </HEAD>\ <body>

<form ld="Form1" method="post" runat="server"> <asp:Repeater id="Repeater1" runat="server"> <HeaderTemplate>

<table wldth="64C" bgcolor="#CC33ff"> <tr bgcolor="#CC33ff"> <td allgn="center"> <font face="Verdana,Arlal" color="#ffff99"> <b>Customer</b> </font> </td>

<td allgn="center"> <font face="Verdana,Arial" color="#ffff99"> <b>Contact Name <br>

<td allgn="center"> <font face="Verdana,Arlal"

color="#ffff99">

<td align="center"> <font face="Verdana,Arial" color="#ffff99"> <b>Password</b> </font> </td>

<td align="center"> <font face="Verdana,Arial" color="#ffff99"> <b>Contract <br>

</HeaderTemplate> <ItemTemplate>

<tr bgcolor="#fffflT' width="200"> <td>

<font face="Verdana,Arial">

<a href='EditCustomer.aspx?CustomerID= <%# DataBinder.Eval(Container.DataItem, "CustomerID") %>'>

<%# DataBinder.Eval(Container.DataItem,

"CompanyName") %> </a> <br>

<%# DataBlnder.Eval(Contalner.DataItem,

<%# DataBlnder.Eval(Contalner.DataItem, "City") %>,

<%# DataBlnder.Eval(Contalner.DataItem,

&nbsp;&nbsp;

<%# DataBlnder.Eval(Contalner.DataItem, "PostalCode") %> </font> </td> <td>

<font face="Verdana,Arlal">

<%# DataBlnder.Eval(Contalner.DataItem,

"ContactFlrstName") %>

<%# DataBlnder.Eval(Contalner.DataItem,

"ContactLastName") %>

<font slze="1"> <%# DataBlnder.Eval(Contalner.DataItem, "ContactEMail") %> </font></font>

<font face="Verdana,Arlal">

<%# DataBlnder.Eval(Contalner.DataItem,

"UserName") %> </font> </td> <td>

<font face="Verdana,Arial">

<%# DataBinder.Eval(Container.DataItem, "Password") %> </font> </td> <td>

<font face="Verdana,Arial">

<%# DataBinder.Eval(Container.DataItem, "ContractEnds","{0:d}") %> </font> </td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr bgcolor="#66ccff"> <td>

<font face="Verdana,Arial">

<a href='EditCustomer.aspx?CustomerID= <%# DataBinder.Eval(Container.DataItem, "CustomerID") %>'>

<%# DataBinder.Eval(Container.DataItem, "CompanyName") %> </a> <br>

<%# DataBinder.Eval(Container.DataItem, "Address") %>

<%# DataBinder.Eval(Container.DataItem, "City") %>,

<%# DataBinder.Eval(Container.DataItem,

&nbsp;&nbsp;

<%# DataBinder.Eval(Container.DataItem, "PostalCode") %> </font> </td> <td>

<font face="Verdana,Arial">

<%# DataBinder.Eval(Container.DataItem,

"ContactFirstName") %>

<%# DataBinder.Eval(Container.DataItem,

"ContactLastName") %>

<font size="1"> <%# DataBinder.Eval(Container.DataItem, "ContactEMail") %> </font></font>

<font face="Verdana,Arial">

<%# DataBinder.Eval(Container.DataItem, "UserName") %> </font> </td> <td>

<font face="Verdana,Arial">

<%# DataBinder.Eval(Container.DataItem, "Password") %> </font> </td> <td>

<font face="Verdana,Arial">

<%# DataBinder.Eval(Container.DataItem, "ContractEnds","{0:d}") %> </font> </td> </tr>

</AlternatingItemTemplate> <FooterTemplate> <tr>

<td colspan=5 align=center>

<a href="EditCustomer.aspx?CustomerID=0"> <img src="AddNew.jpg" Alt="Add New"></a> </td> </tr> </table> </FooterTemplate>

<asp:Label id="Label1" runat="server"></asp:Label>

Caution

Because the

Repeate r control allows you to specify incompl ete

HTML within individu al element s such as a

<TABLE > start tag without a nearby, properly nested end tag, you may not be able to display a page with a Repeate r control in the Visual Studio .NET Design view. Because of the way that the

Repeate r control renders when run, the resulting

HTML

will be correct.

You can edit pages with a

Repeate r control in HTML

view.

The error messag es that appear when you try to switch to

Design view will not always make it obvious what the problem is.

The code in RepeaterTest.aspx is fairly simple HTML interspersed with ASP.NET tags. Different in this example is the method used to bind data to the Repeater control. All data is bound using the Eval method of the DataBinder class. All data binding is done within the <%# %> delimiters.

Note The <%# %> delimiters are used only for data binding. The expression inside these delimiters is evaluated whenever DataBind is called. This syntax is different from the ASP syntax for displaying the contents of a variable—for example, <%=foo%>. The <%= %> delimiters are still supported, but they're not used in data binding.

The Eval method has two overloads, both of which are used in this example. The syntax for the first overload is shown here:

[Visual Basic.NET]

Overloads Public Shared Function Eval( _ ByVal container As Object, _ ByVal expression As String _ ) As Object [C#]

public static object Eval( object container, string expression

The container parameter is the object reference that the expression is evaluated against. In all the uses of Eval in Listing 9-4, container is Container.DataItem. This refers back to the DataSource property of the Repeater control. The second parameter, expression, is the field name, as it appears in the data source. Spelling does count, and the syntax for the expression can be more complex if instead of a DataReader object you're using a DataSet object. For example, the syntax could be

Tables[0].DefaultView.[0].CompanyName rather than simply CompanyName, as DataSet objects can refer to multiple tables.

The second overload to the Eval method is as follows, with an additional string: [Visual Basic.NET]

Overloads Public Shared Function Eval( _ ByVal container As Object, _

ByVal expression As String, _ ByVal format As String _ ) As String [C#]

public static string Eval( object container, string expression, string format

The additional parameter, format, is a standard .NET Framework format string. For example, the following code snippet, from Listing 9-4, will use the DataSource property of the containing Repeater control, get the ContractEnds field, and format it as a date:

<%# DataBinder.Eval(Container.DataItem,

The MSDN documentation contains complete documentation on format strings. Listing 9-4 uses all of the templates described in Table 9-2 except SeparatorTemplate. ltemTemplate and AlternatingltemTemplate are identical, except for the background color on the <tr> tags. HeaderTemplate contains the start tag of the HTML table element as well as a row of headers. FooterTemplate contains the row that holds the image to allow you to add a new record, as well as the HTML table end tag. RepeaterTest.aspx includes several HTML anchor tags to link to another form, named EditCustomer.aspx. More on that form later in this chapter, in the section "Creating Data Entry Pages."

Tip One problem I noticed initially in RepeaterTest.aspx was that Visual

Studio .NET was reformatting my code in a way that caused problems. For example, an extra space was appearing between the first name and the last name. The culprit was the addition of an unwanted line break between the binding code for the first name and the last name that was somehow causing an additional space in the output. The solution is to choose Options on the Tools menu, and in the Options dialog box, navigate to Text Editor and then HTML/XML and Format. Then clear the Apply Automatic Formatting: When Saving Document and When Switching From Design To HTML/XML View check boxes. This is the first project I've worked on in which the automatic formatting caused me any pain, but I'll leave it off for now, just to be safe. There are a number of settings that can make the text editor easier to use that you should investigate in the Options dialog box. RepeaterTest.aspx also has a code-behind file, named RepeaterTest.aspx.cs, shown in Listing 9-5.

Listing 9-5 RepeaterTest.aspx.cs, the code-behind file for the Repeater class test page using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace Chapter09_Template {

III <summary>

III Summary description for WebForml. III <Isummary>

public class WebForml : System.Web.UI.Page {

protected System.Web.UI.WebControls.Repeater Repeaterl; protected System.Web.UI.WebControls.Label Labell; protected System.Data.SqlClient.SqlCommand cmd;

public WebForm1() {

Page.Init += new System.EventHandler(Page_Init);

private void Page_Load(object sender, System.EventArgs e) {

SqlConnection cn = new SqlConnection("server=localhost;" +

"Integrated Security=SSPI;Initial Catalog=GolfArticles"); SqlCommand cmd; cmd=new SqlCommand(

"Select * from Customer Order By CompanyName",cn);

Repeater1.DataSource= cmd.ExecuteReader( CommandBehavior.CloseConnection);

this.DataBind();

catch (System.Exception eLoad) {

Label1.Text=eLoad.Message;

private void Page_Init(object sender, EventArgs e) {

// CODEGEN: This call is required by the // ASP.NET Web Form Designer.

InitializeComponent();

#region Web Form Designer generated code /// <summary>

/// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary>

private void InitializeComponent() {

this.Load += new System.EventHandler(this.Page_Load);

#endregion

RepeaterTest.aspx.cs has a single method that contains code critical to the operation of the Repeater control. In the Page_Load method, the following lines are most important:

Repeater1.DataSource= cmd.ExecuteReader( CommandBehavior.CloseConnection);

this.DataBind();

First I open the previously created connection object. Next I set the DataSource property of the Repeater object to the return value from the ExecuteReader method of the SqlCommandobject. ExecuteReader returns a DataReader object, and because I specify CommandBehavior.CloseConnection, the connection will be closed when the data reader is closed. Finally, I call DataBind. Once again, without this call, the data won't be bound, and nothing will be displayed in the Repeater control. And again, this code won't be added by the .NET Framework, nor by Visual Studio .NET. Whenever bound data doesn't appear, checking to see that DataBind is actually called (and called at the correct level) is critical.

Using Caching to Improve Performance and Scalability

Using Caching to Improve Performance and Scalability

One feature of ASP.NET that can improve the performance and scalability of applications displaying dynamic data is output caching. Say that you add the following line to an aspx page:

<%@ OutputCache Duration="20" VaryByParam="None" %>

When the page is requested, rather than actually running the underlying code, the page is served up directly from the ASP.NET cache. For pages that are expensive to generate but that don't change frequently, output caching can provide a huge performance benefit.

In the example OutputCache directive above, when the page is requested for the first time, the .NET Framework will run whatever code is required to generate the page. Anyone rerunning the page within the next 20 seconds (as specified by the Duration attribute) will get the cached copy rather than a copy created by rerunning the underlying code. The first client to request the page after the 20 seconds have expired will get a newly created copy of the page.

Often, a page will be called with one or more parameters, and the parameters might change the content that is displayed. For that common scenario, the VaryByParam attribute allows you to specify a semicolon-delimited list of parameters, or "*" for all parameters. When parameters or "*" is specified for VaryByParam, a separate copy of the page is cached for each set of parameters specified—or for each set of all parameters, if "*" is specified.

The same logic can be used to cache a fragment of a page. The OutputCache directive is also available for user controls.

ASP.NET caching works only with ASP.NET Premium edition installed on the server.

Was this article helpful?

0 0

Post a comment