Team LiB
Previous Section Next Section

Data Binding Samples

This next section shows you some samples that involve basic ASP.NET Web Forms data binding. You will see how to bind data to simple properties, how to list type controls such as the Repeater and DataList, and finally you will see an example of using the ASP.NET DataGrid control in a data-bound situation.

Simple Binding

You have already seen plenty of examples of simple binding in this chapter. Whenever you use the <%# %> syntax to evaluate some expression in the ASP.NET page at bind time, you are using simple binding. A section is included here just as a refresher to remind you that you can accomplish some pretty amazing things using just simple data binding. You should always try to look for the simplest solution to any problem, and simple binding is often overlooked in favor of more complex binding.

Repeater Binding

The Repeater is a simple control that enables you to define output that will be repeated for each element in the bound list. You can define templates for the header, default items, alternating items (every even numbered element), separators between each element, and even the footer. The Repeater is an incredibly flexible control that can be used to display virtually anything that is described by list data. It is also the most basic control and contains the least amount of built-in functionality.

Listing 31.3 shows a Repeater control defined by an ASP.NET page, followed by the code-behind class in Listing 31.4. This chapter doesn't spend too much time on templates and template programming because that topic is better covered by chapters on developing GUI controls.

Listing 31.3. An ASP.NET Page Demonstrating the Use of a Data-Bound Repeater
<%@ Page language="c#"
    Codebehind="RepeaterDemo.aspx.cs"
    AutoEventWireup="false"
    Inherits="WebFormsBinding.RepeaterDemo" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
  <title>RepeaterDemo</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema"
       content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>

<body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" runat="server">
  <asp:Repeater ID="rptCustomer" Runat="server">
    <HeaderTemplate>
     <table width="100%" border="0" cellspacing="1" cellpadding="1">
     <tr>
      <th>
       Contact Name</th>
      <th>
       Company Name</th>
      <th>
       Contact Title</th>
    </tr>
   </HeaderTemplate>
   <FooterTemplate>
     </table>
   </FooterTemplate>
   <ItemTemplate>
     <tr>
       <td><%# DataBinder.Eval(Container.DataItem, "ContactName") %></td>
       <td><%# DataBinder.Eval(Container.DataItem, "CompanyName") %></td>
       <td><%# DataBinder.Eval(Container.DataItem, "ContactTitle") %></td>
    </tr>
   </ItemTemplate>
   <SeparatorTemplate>
     <tr>
       <td colspan="3"><hr>
       </td>
     </tr>
   </SeparatorTemplate>
   <AlternatingItemTemplate>
     <tr bgcolor="#c8c8c8">
       <td><%# DataBinder.Eval(Container.DataItem, "ContactName") %></td>
       <td><%# DataBinder.Eval(Container.DataItem, "CompanyName") %></td>
       <td><%# DataBinder.Eval(Container.DataItem, "ContactTitle") %></td>
     </tr>
   </AlternatingItemTemplate>
</asp:Repeater>
</form>
</body>
</HTML>

Listing 31.4. The Code-Behind for the ASP.NET Page in Listing 31.3
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 WebFormsBinding
{
  public class RepeaterDemo : System.Web.UI.Page
  {
    protected System.Web.UI.WebControls.Repeater rptCustomer;

    private void Page_Load(object sender, System.EventArgs e)
    {
      SqlConnection conn = new SqlConnection(
        "server=localhost; user id=sa; password=password; Initial Catalog=Northwind;");
      conn.Open();
      SqlDataAdapter da=  new SqlDataAdapter("SELECT * FROM Customers", conn);
      DataSet ds = new DataSet();
      da.Fill(ds,"Customers");

      rptCustomer.DataSource = ds;
      DataBind();
    }

    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      InitializeComponent();
      base.OnInit(e);
    }

    private void InitializeComponent()
    {
      this.Load += new System.EventHandler(this.Page_Load);

    }
    #endregion
  }
}

Figure 31.1 shows what the output of this page looks like. As you would expect, it is a simple repetition of customers from the Northwind database, separated by <hr> tags and distinguished with a differing background color for alternating items.

Figure 31.1. A Repeater control with an ItemTemplate and an AlternatingItemTemplate.


DataList Binding

The DataList is derived from the Repeater, but it adds quite a bit of functionality. Not only can you repeat items, but the DataList also enables you to flow items in a given direction. You can choose to have the items appear in sequence horizontally or vertically, and move to the next region of display space after presenting a certain number of items. In this way, you can simulate a display such as a newspaper column layout, and you also can create attractive photo thumbnail displays, product overview displays, and more. The RepeatDirection property controls the direction in which the DataList flows, and the RepeatColumns property indicates the number of items to display before switching (or breaking) to the next repeat of items. If you are flowing vertically, the next repeat of items is a column. If you are flowing horizontally, the next repeat of items will be in a new row.

Listing 31.5 shows that you can create a very attractive flow of data, and you can define visual styles for the items, alternating items, headers, and footers. Styles like that cannot be defined by the Repeater, and this is one area in which the DataList shows off its power. In Listing 31.5, you will see the ASP.NET markup that creates a powerful DataList control. The binding code is not shown because it is virtually identical to the binding code in Listing 31.4.

Listing 31.5. An ASP.NET Page Demonstrating a Data-Bound DataList Control
   <%@ Page language="c#" Codebehind="DataListDemo.aspx.cs"
       AutoEventWireup="false" Inherits="WebFormsBinding.DataListDemo" %>
   <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
   <HTML>
   <HEAD>
     <title>DataListDemo</title>
     <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
     <meta name="CODE_LANGUAGE" Content="C#">
     <meta name="vs_defaultClientScript" content="JavaScript">
     <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
   </HEAD>
   <body>

   <form id="Form1" method="post" runat="server">

     <asp:DataList ID="dlCustomers" Runat="server"
         RepeatColumns="3" RepeatDirection="Horizontal"
         AlternatingItemStyle-BackColor="#c8c8c8" ItemStyle-Height=150>
       <ItemTemplate>
         <table width="100%" border="1"
           bordercolor="#000000" cellspacing="0" cellpadding="0" height=150>
         <tr>
           <td valign="top">
             <table width="100%" border="0" cellspacing="2" cellpadding="2">
               <tr>
                <td colspan="2" align=center>
                 <b><%# DataBinder.Eval(Container.DataItem, "ContactName")%></b>
                </td>
              </tr>
              <tr>
                <td width="50%" >
                 <%# DataBinder.Eval(Container.DataItem, "CompanyName")%>
                </td>
                <td width="50%" >
                  <%# DataBinder.Eval(Container.DataItem, "ContactTitle")%>
                </td>
              </tr>
              <tr>
               <td colspan="2">
                 <%# DataBinder.Eval(Container.DataItem, "Address") %>
                 <br>
                 <%# DataBinder.Eval(Container.DataItem, "City") %>,
                 <%# DataBinder.Eval(Container.DataItem, "PostalCode") %>
               </td>
              </tr>
          </table>
         </td>
       </tr>
    </table>
    </ItemTemplate>

    <HeaderTemplate>
    </HeaderTemplate>
    <FooterTemplate>
    </FooterTemplate>
   </asp:DataList>
   </form>
   </body>
   </HTML>

From the preceding code, you should be able to see that each item is a self-contained table with its own border and a nested table to create a surrounding margin . Within the table, the contact name is centered above the contact information, such as the address and postal code. The effect looks very much like a business card. Figure 31.2 shows the (much more attractive) output produced by the DataList.

Figure 31.2. A DataList control bound to data with an ItemTemplate.


DataGrid Binding

The DataGrid is a complex and powerful control. It contains all the capability to visually style items that the DataList has and much more. It is designed to present data as a list of rows, with each row containing one or more columns. This output looks just like a worksheet in Excel. Not too much time will be spent on the basics of DataGrid binding because the advanced samples will cover many of the details of how to manipulate a DataGrid.

    Team LiB
    Previous Section Next Section