日期:2011-03-14  浏览次数:20416 次

The .NET Framework Beta 2 has many changes that will break applications written in Beta 1. Among these changes is the templates used in Data Server Controls, such as the DataGrid and DataList. These are simply syntax changes in how templates are used, not programmatic breaks. In this tutorial you will learn how to use Data Server Control templates. Heck, since its a Friday I'll also show you how to do DataGrid editing at the same time. The downloadable sample code for this article contains files in both Visual Basic.NET and C#.

What Good is a Template?

Templates can be used with the Data Server Controls to provide a custom layout of the data bound to the control. The DataGrid provides a basic grid, with one row for each record, and one table column for each field in the row. Templates can be used with a TemplateColumn to custom format the layout of the column. The DataList provides one row for each record in the data source, and templates are used to format the layout of each row. The Repeater control is entirely custom. Templates are used to provide the layout for the entire Repeater control.

Changing a Name is a Big Deal

In Beta 1 you would use a DataGrid, and set up templates using a TemplateColumn. This is the same in Beta 2, however there are some slight changes to the syntax. In Beta 1 a DataGrid using a TemplateColumn would look like the code in Listing 1.

Listing 1

<asp:DataGrid runat="server" id="myGrid"
  AutoGenerateColumns="False" >
  <property name="columns">
    <asp:TemplateColumn HeaderText="Info">
      <template name="ItemTemplate">
        <b><%# DataBinder.Eval(Container.DataItem,"CompanyName") %></b><br>
        <%# DataBinder.Eval(Container.DataItem, "ContactName")%>
        -
        <%# DataBinder.Eval(Container.DataItem, "ContactTitle")%><br>
        <%# DataBinder.Eval(Container.DataItem, "Address")%><br>
        <%# DataBinder.Eval(Container.DataItem, "City") %>,
        <%# DataBinder.Eval(Container.DataItem, "Region") %>
        <%# DataBinder.Eval(Container.DataItem, "PostalCode") %>
      </template>
    </asp:TemplateColumn>
  </property>
</asp:DataGrid>  

The majority of the syntax in Listing 1 remains the same. The changes are as follows:

The <property> element changes to <Columns>
The <template> element changes to one of the following:
<AlternatingItemTemplate>
<EditItemTemplate>
<FooterTempalte>
<HeaderTemplate>
<ItemTemplate>
<SeparatorTemplate> (Repeater and DataList)
The same DataGrid shown in Listing 1 can be updated to Beta 2 as shown in Listing 2.

Listing 2

Listing 1

<asp:DataGrid runat="server" id="myGrid"
  AutoGenerateColumns="False" >
  <Columns>
    <asp:TemplateColumn HeaderText="Info">
      <ItemTemplate>
        <b><%# DataBinder.Eval(Container.DataItem, "CompanyName") %></b><br>
        <%# DataBinder.Eval(Container.DataItem, "ContactName") %>
        -
  &nb