Using Templated Controls to Display Data

A template is a set of HTML elements and controls that collectively specify the layout for a control. A control that supports templates is known as a templated control. ASP.NET implements three templated controls: Repeater , DataList , and DataGrid .

The DataGrid control has a default look and feel that can be customized with the use of templates, but the Repeater and DataList controls have no default rendering, and their displays are entirely dictated by templates.

The Repeater Control

The Repeater control is a data-bound container control that produces a list of individual items. You use templates to define a customized layout of its items. The following example shows how:

  1. Add a new Visual C# ASP.NET Web Application project named Example6_8 to the current solution. Place a Repeater control ( rptOrders ) on the Web form.

  2. Drag the Orders table from the Northwind sample database and drop it on the form. This creates two visual data objects: sqlConnection1 and sqlDataAdapter1 .

  3. Select the sqlDataAdapter1 object and click the Generate Dataset link below the Properties window. Create a new dataset named dsOrders .

  4. Set the DataSource property of the Repeater control to dsOrders1 . Set the DataMember property of the Repeater control to Orders .

  5. Switch to HTML view and enter the following code to customize the Repeater control:

     <asp:Repeater id="rptOrders" runat="server"  DataSource="<%# dsOrders1 %>" DataMember="Orders">     <HeaderTemplate>         <table>             <thead bgcolor=#6699ff>                 <th>Order ID</th>                 <th>Customer ID</th>                 <th>Order Date</th>                 <th>Freight</th>             </thead>     </HeaderTemplate>     <ItemTemplate>       <tr bgcolor=#ccffff>          <td><%# DataBinder.Eval(Container.DataItem, "OrderID") %></td>          <td><%# DataBinder.Eval(Container.DataItem, "CustomerID")              %></td>          <td><%# DataBinder.Eval(Container.DataItem, "OrderDate", "{0:d}")%></td>          <td><%# DataBinder.Eval(Container.DataItem, "Freight", "{0:c}")%></td>       </tr>     </ItemTemplate>     <AlternatingItemTemplate>       <tr bgcolor=#ffffff>         <td><%# DataBinder.Eval(Container.DataItem, "OrderID") %></td>         <td><%# DataBinder.Eval(Container.DataItem, "CustomerID")%></td>         <td><%# DataBinder.Eval(Container.DataItem, "OrderDate", "{0:d}")%></td>         <td><%# DataBinder.Eval(Container.DataItem, "Freight", "{0:c}")%></td>         </tr>     </AlternatingItemTemplate>     <SeparatorTemplate>         <tr height=4 bgcolor=#0000ff>             <td></td><td></td><td></td><td></td>         </tr>     </SeparatorTemplate>     <FooterTemplate>         </table>     </FooterTemplate> </asp:Repeater> 
  6. Switch to Code view and add the following code to the Page_Load() event handler:

     private void Page_Load(object sender, System.EventArgs e) {     sqlDataAdapter1.Fill(dsOrders1, "Orders");     DataBind(); } 
  7. Set the project as the startup project and run the project. The Repeater control displays data from four columns of the Orders table, as shown in Figure 6.6.

    Figure 6.6. The Repeater control offers flexible formatting options for tabular data.

    graphics/06fig06.jpg

If you inspect the HTML, you'll see that the Repeater control allows you to specify five templates:

  • The HeaderTemplate is rendered once at the start of the control.

  • The ItemTemplate is rendered once for every row of data in the data source of the control.

  • The AlternatingItemTemplate is used instead of the ItemTemplate for every other row of data. If you omit the AlternatingItemTemplate , the ItemTemplate is used for all rows.

  • The SeparatorTemplate is rendered once between each row of data.

  • The FooterTemplate is rendered once at the end of the control.

The only one of these templates that you're required to implement for a Repeater control is the ItemTemplate . You can perform data binding only in the ItemTemplate and AlternatingItemTemplate templates.

You'll also see a new object in the HTML code: the DataBinder . DataBinder exists to format data in templated controls (and other controls that contain subcontrols). The Eval() method of the DataBinder object takes three arguments:

  • The first argument specifies the source of the data. The templates are contained in the Repeater control, and the Repeater control itself is bound to a collection of data. So in this case, the source of the data is Container.DataItem , a single item of data from the containing control.

  • The second argument is the name of a column in the data to bind at this position.

  • The third (optional) argument is a format string, of the type that could be supplied to the String.Format() method.

The DataBinder object handles all the necessary casting to make string formatting work properly with bound data, regardless of the data type of the underlying data.

graphics/note_icon.gif

The best thing about the DataBinder.Eval() method is that it saves you from writing complex expressions. However, using this method does impose a performance penalty on your code because all the work it does is late-bound . If you want the fastest possible code, you can replace calls to DataBinder.Eval() with explicit casts. For example, consider this binding expression:


<%# DataBinder.Eval(Container.DataItem, "Freight", "{ 0:c} ") %>
An equivalent expression using casts would be this:
<%# String.Format("{ 0:c} ",
   ((DataRowView) Container.DataItem)["Freight"]) %>


The DataList Control

The DataList control is similar to the Repeater control, but it provides more flexible formatting options. The control handles the layout of items in rows and columns, so you don't have to supply <table> tags in its templates. It also lets you build data-editing capabilities into the Web form.

In addition to the five templates supported by the Repeater control, DataList also allows you to set a SelectedItemTemplate to indicate a current row in the data and an EditItemTemplate that is used to render data being edited by the user . Unlike Repeater , however, DataList supports formatting templates directly in the Visual Studio .NET IDE. The following example shows how to apply templates on the DataList control to display data:

  1. Add a new Visual C# ASP.NET Web Application project named Example6_9 to the current solution.

  2. Place a DataList control ( dlOrders ) on the new Web form. Set the RepeatColumns property of the DataList control to 2 and the CellSpacing property of the control to 10 .

  3. Drag the Orders table from the Northwind sample database and drop it on the form. This creates two visual data objects: sqlConnection1 and sqlDataAdapter1 .

  4. Select the sqlDataAdapter1 object and click the Generate Dataset link below the Properties window. In the Generate Dataset window, create a new dataset object named dsOrders .

  5. Set the DataSource property of the Repeater control to dsOrders1 . Set the DataMember property of the Repeater control to Orders .

  6. Switch to HTML view and enter the following code to customize the DataList control. Note the <DIV> tags in the ItemTemplate , which are essential to preserve formatting:

     <asp:DataList id="dlOrders" runat="server"     DataSource="<%# dsOrders1 %>" DataMember="Orders"     RepeatColumns="2" CellSpacing="10">    <ItemTemplate><div>       <b>Order ID: </b>       <%# DataBinder.Eval(Container.DataItem, "OrderID") %>       <br> <b>Customer ID: </b>       <%# DataBinder.Eval(Container.DataItem, "CustomerID") %>       <br> <b>Order Date: </b>       <%# DataBinder.Eval(Container.DataItem, "OrderDate", "{0:d}") %>       <br> <b>Freight: </b>       <%# DataBinder.Eval(Container.DataItem, "Freight", "{0:c}") %>       <br></div>    </ItemTemplate> </asp:DataList> 
  7. Switch back to Design view. Right-click the DataList control and select Edit Template, Item Templates.

  8. Click in the ItemTemplate area, below the text, so that you can see the properties for the <DIV> tag that wraps this template in the Properties window. Click in the Style property and click the builder () button to open the Style Builder dialog box. Use the Style Builder to set the font and color properties as you like; then click OK.

  9. Select all the text in the ItemTemplate , copy it, and paste a copy into the AlternatingItemTemplate . Use the Style Builder to set the properties for the AlternatingItemTemplate .

  10. Switch to Code view and add the following code to the Page_Load() event handler:

     private void Page_Load(object sender, System.EventArgs e) {     sqlDataAdapter1.Fill(dsOrders1, "Orders");     dlOrders.DataBind(); } 
  11. Set the project as the startup project for the solution and run the project. The DataList control displays data in two columns. The number of columns is controlled by the RepeatColumns property of DataList . Also, each item is rendered according to the formatting you specified in the Style Builder.

Editing Data with a DataList Control

The DataList control also offers support for editing data. To enable this support, you need to supply an EditItemTemplate and respond properly to several events as demonstrated in the following example:

  1. Add a new Visual C# ASP.NET Web Application project named Example6_10 to the current solution. Place a DataList control ( dlOrders ) on the Web form. Set the RepeatColumns property of the control to 1 and the CellSpacing property of the control to 10 .

  2. Bind dlOrders to the dsOrders DataSet object.

  3. Switch to HTML view and enter the following code to customize the DataList control. This code includes an EditItemTemplate with a control to edit the freight charge for a row:

     <asp:DataList id="dlOrders" runat="server" DataSource="<%# dsOrders1%>"     DataMember="Orders" RepeatColumns="1"  CellSpacing="10">     <ItemTemplate>       <b>Order ID: </b>       <%# DataBinder.Eval(Container.DataItem, "OrderID") %>       <br><b>Customer ID: </b>       <%# DataBinder.Eval(Container.DataItem, "CustomerID") %>       <br><b>Order Date: </b>       <%# DataBinder.Eval(Container.DataItem, "OrderDate", "{0:d}") %>       <br><b>Freight: </b>       <%# DataBinder.Eval(Container.DataItem, "Freight", "{0:c}") %>       <br><asp:Button id="btnEdit" runat="server"          Text="Edit" CommandName="Edit"></asp:Button>     </ItemTemplate>     <EditItemTemplate>        <b>Order ID: </b>        <%# DataBinder.Eval(Container.DataItem, "OrderID") %>        <br><b>Customer ID: </b>        <%# DataBinder.Eval(Container.DataItem, "CustomerID") %>        <br><b>Order Date: </b>        <%# DataBinder.Eval(Container.DataItem, "OrderDate", "{0:d}") %>        <br><b>Freight: </b><input id=freight type=text          runat="server" value='<%# DataBinder.Eval(Container.DataItem, "Freight") %>' >        <br><asp:Button id="btnUpdate" runat="server"         Text="Update" CommandName="Update"></asp:Button>        <asp:Button id="btnCancel" runat="server"         Text="Cancel" CommandName="Cancel"></asp:Button>     </EditItemTemplate> </asp:DataList> 
  4. Switch to Code view and add the following code to the Page_Load() event handler:

     private void Page_Load(object sender, System.EventArgs e) {     // Load the data     if(!IsPostBack)     {         sqlDataAdapter1.Fill(dsOrders1, "Orders");         DataBind();     } } 
  5. Attach event handlers for the CancelCommand , EditCommand , UpdateCommand , events of the DataList control, and add the following code to the event handlers:

     private void dlOrders_CancelCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e) {     // Turn off the editing controls     dlOrders.EditItemIndex = -1;     // Re-bind the data     sqlDataAdapter1.Fill(dsOrders1, "Orders");     DataBind(); } private void dlOrders_EditCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e) {     // Turn on the editing controls     dlOrders.EditItemIndex = e.Item.ItemIndex;     // Re-bind the data     sqlDataAdapter1.Fill(dsOrders1, "Orders");     DataBind(); } private void dlOrders_UpdateCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e) {     HtmlInputText htEdit;     // Get the existing data     sqlDataAdapter1.Fill(dsOrders1, "Orders");     // Get the changed data and put it in the database     htEdit = (HtmlInputText)e.Item.FindControl("freight");     dsOrders1.Tables["Orders"].Rows[          e.Item.ItemIndex][7] = htEdit.Value;     // Turn off editing     dlOrders.EditItemIndex = -1;     // re-bind the data     DataBind(); } 
  6. Set the project as the startup project for the solution and run the project. The DataList control displays data from four columns of the Orders table. Click the Edit button for any row, and you'll be able to edit the Freight value.

After you've created a DataList with an EditItemTemplate , you can tell the control to use that template for a specific row by supplying the ( zero-based ) index of that row. The CommandName tags in the HTML code correspond to the events that DataList raises in the C# code. When you raise an EditCommand event, the parameters passed to the event include the data item in which the event was raised. The code uses the index of this item to determine which row to show in the edited state (using the Item.ItemIndex property of the DataListCommandEventArgs object). Note that you need to rebind the data when you do this because in reality, you're rebuilding the entire page from scratch.

To cancel an edit, set the EditItemIndex property back to -1 and rebind the control.

To update the data, the code uses the FindControl() method of the data item to find the input control where the freight value was edited. This control can be represented by an HtmlInputText object in the code. The code then uses the Value property of that object to update the corresponding row in the DataSet object.

graphics/note_icon.gif

The DataList control also has a SelectedIndex property that can be used to highlight a particular row in the DataList control. Similar to the EditItemIndex property, the SelectedIndex property is zero based. If you set SelectedItemIndex to 3 , for example, the fourth row in the DataList control is displayed using SelectedItemTemplate .




MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
ISBN: 789729016
EAN: N/A
Year: 2005
Pages: 191

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