Header Ads

Using the New ListView Control in ASP.NET 3.5

user-focused application that you write requires some sort of data integration. At minimum, you will need to retrieve some data from a data source such as a relational database or an XML file, and format it before displaying it in the user interface. Although previous versions of ASP.NET provided data-centric display controls such as GridView, these controls lacked the customization and extensibility features required by a professional web developer. To address this shortcoming, the ASP.NET 3.5 provides a new control named ListView that provides excellent customization and extensibility features. Using these features, you can display data in any format, using templates and styles, and also perform CRUD (Create, Read, Update, and Delete) activities with minimal code.

This article focuses on the data access steps involved in using the new ListView control, and includes advanced features such as editing data and handling events.

A Primer on the ListView Control
Most data-bound controls supplied with ASP.NET automatically enclose the displayed data with additional markup. As an example, the GridView control displays its data rendered inside of an HTML table (
), displaying each record of data bound to it as a table row () and each record field as a cell within the row (
). While you can use TemplateField elements and other tools to customize the appearance of a GridView, the GridView's output will still be enclosed within a table element. But sometimes you want to have complete control over the appearance of the HTML markup generated by the data-bound controls. This is exactly where the ListView control comes into play. The ListView control does not automatically enclose its rendered output in any additional markup. Instead, it's your responsibility to specify the precise HTML rendered for the ListView control. You specify the precise markup using the ListView's built-in templates. Table 1 lists the templates supported by the ListView control.

Table 1. ListView Templates: The ListView control supports these templates.
Template Purpose
AlternatingItemTemplate Display alternating items with different markup to help viewers distinguish consecutive items.
EditItemTemplate Controls display when an item is in edit mode.
EmptyDataTemplate Controls display when the ListView's data source returns no data.
EmptyItemTemplate Controls the display for an empty item.
GroupSeparatorTemplate Controls the content to display between groups of items.
GroupTemplate Specifies a container object such as a table row, div, or span element for the content.
InsertItemTemplate Specifies content to render when users insert an item.
ItemSeparatorTemplate Controls the content to display between individual items.
ItemTemplate Controls content to display for individual items.
LayoutTemplate Specifies the root element that defines a container object, such as a table, div, or span element that surrounds content defined in the ItemTemplate or GroupTemplate.
SelectedItemTemplate Specifies the content to display for the currently selected item.

The two key templates are the LayoutTemplate and ItemTemplate. As the name suggests, the LayoutTemplate specifies the overall markup for the ListView control, while the ItemTemplate specifies the markup used to display each bound record. For example, the following code displays a list of items within an HTML table control in a ListView:

<asp:ListView ID="..." runat="server" DataSourceID="...">

 <LayoutTemplate>

  <table â�¦â�¦.>

   <tr runat="server" ID="itemPlaceholder"></tr>

  </table>

 </LayoutTemplate>

 <ItemTemplate>

  <tr>

   <td><%# Eval("Name") %></td>

  </tr>

 </ItemTemplate>

</asp:ListView>

In the preceding code, the ID of the

control inside the LayoutTemplate control is set to itemPlaceHolder, which tells the ListView to place content generated through the ItemTemplate control inside the control. This is required because you define the LayoutTemplate and ItemTemplate separately. A Simple Data-Binding Example Now that you have seen the various templates supported by ListView control, the next step is to create a new sample web site. Name it ListViewExample (you can download the sample code here). After creating the web site, select Website → Add New Item from the menu to add a new ASP.NET page named SimpleListView.aspx (see Listing 1). This page will use the ListView control to display products data from the Product table in the AdventureWorks sample database. In Listing 1, the SqlDataSource control retrieves data from the Product table of the TestDb database by setting the ConnectionString and SelectCommand properties to appropriate values. The ConnectionString property obtains the connection string from the web.config file through an ASP.NET expression. On my test machine, the connection string is defined in web.config as:

<connectionStrings>     <add name="AdventureWorks"        connectionString="server=localhost;uid=sa;      pwd=sa;database=TestDb;"/>     </connectionStrings>
After setting the SqlDataSource properties, the next step is to display that data through the ListView control. Here's the markup contained in the LayoutTemplate:
<LayoutTemplate>     <table cellpadding="2" runat="server" id="tblProducts"       style="width:460px">      <tr runat="server" id="itemPlaceholder">      </tr>     </table>     <asp:DataPager runat="server" ID="DataPager" PageSize="3">      <Fields>       <asp:NumericPagerField ButtonCount="10"         PreviousPageText="<--" NextPageText="-->" />      </Fields>     </asp:DataPager>    </LayoutTemplate>
The LayoutTemplate defines the container for the output generated through the ListView control. In addition to the table control that defines the overall layout of the ListView control, the LayoutTemplate also defines the control, which provides paging functionality for the ListView control. The DataPager control lets you page data and display navigation controls for any data-bound control that implements the IPageableItemContainer interface (which the ListView control does). There are two ways to associate the DataPager control with a data-bound control: 1. Set the PagedControlID property of the DataPager control to the name of the data-bound control. 2. Place the DataPager control inside the data-bound control hierarchy. For the ListView control, you can put the DataPager control inside the LayoutTemplate element. Setting the DataPager's PageSize property controls the number of items displayed for each page of data. You can also change the way a page is submitted to the server by setting the QueryStringField property. Figure 1. Simple ListView: Here's the output produced by data-binding the ListView control to a SqlDataSource control that retrieves some Product data. Inside the DataPager control, you specify the NumericPageField template, which enables users to navigate to a particular page by selecting a page number.
<asp:NumericPagerField ButtonCount="10"        PreviousPageText="<--"       NextPageText="-->" />
The ItemTemplate element provides the markup for each record's details by retrieving the data from the data source control through the Eval() statement. Figure 1 shows the output produced by navigating to the page in the browser. Editing Data with the ListView Control As you've seen, displaying data through a ListView control is relatively straightforward, but you can let users edit the data in a ListView as well. Add a new ASP.NET page named ListViewEditExample.aspx to the sample web site and modify its code as shown in Listing 2: The code in Listing 2 demonstrates how to use the EditItemTemplate element to generate content when an item is in edit mode, and update the database through the SqlDataSource control. First, you set the UpdateCommand property of the SqlDataSource control to the SQL statement that will be executed to update the database with the latest values specified by the user:
<asp:SqlDataSource ID="deptSource" runat="server"         ConnectionString="<%$ ConnectionStrings:AdventureWorks %>"        SelectCommand="SELECT [DepartmentID],[Name],[GroupName] FROM         HumanResources.Department" UpdateCommand="UPDATE         HumanResources.Department SET Name = @Name,        GroupName = @GroupName WHERE DepartmentID = @DepartmentID">       </asp:SqlDataSource>
Next, in the ItemTemplate element, you specify the link users click to edit an item:
<ItemTemplate>           <asp:LinkButton ID="btnEdit" runat="Server" Text="Edit"         CommandName="Edit" />      </td>     </tr>    </ItemTemplate>
After that, you specify the EditItemTemplate that declares the text boxes where users enter the update Name and/or GroupName of the department, and the links for the users to either commit ("Update") or cancel ("Cancel") the current operation.
<EditItemTemplate>     <tr style="background-color: #ADD8E6">                  <td>       <asp:TextBox ID="txtName" runat="server"         Text='<%# Bind("Name") %>'         MaxLength="50" /><br />      </td>      <td>       <asp:TextBox ID="txtGroupName" runat="server" Text='<%#         Bind("GroupName") %>' MaxLength="50" /><br />      </td>      <td>       <asp:LinkButton ID="btnUpdate" runat="server"         CommandName="Update" Text="Update" />&nbsp;       <asp:LinkButton ID="btnCancel" runat="server"         CommandName="Cancel" Text="Cancel" />      </td>     </tr>    </EditItemTemplate>
You define the LinkButton's action by setting the CommandName property to an appropriate value, as shown in Table 2. Table 2. LinkButton CommandName Values: Here's a list of the acceptable values for the CommandName property that control ListView behavior. Value Description Cancel Cancels the current operation. Delete Deletes the currently selected item from the data source. Edit Switches the ListView to edit mode, and displays the content specified in the EditItemTemplate element. Insert Saves the values in the data source control to the data source as a new record. Update Updates the data source with the values in the data source control. At the end of the update, the ListView control fires an OnItemUpdated event that you can use to confirm the update status to users. In the code in Listing 2, the ListView control handles two events: Figure 2. Editable ListView in Action: The configured ListView control displays an Edit link for each record. Clicking that link switches the contents of the ListView control to edit mode. * OnItemUpdated: As the name suggests, this event allows you to perform a custom routine at the end of an update operation. In the preceding code, this event is used to inform users of the number of records affected. * OnPagePropertiesChanged: The ListView fires this event when the page properties change. The code in Listing uses this event to clear out the text contained in the label control. With the ListView configured, if you navigate to the page with a browser you should see an output similar to Figure 2: When you click on the Edit hyperlink, the ListView uses the EditItemTemplate to display the textboxes where users can edit the selected item, as shown in Figure 3. Figure 3. Edit Mode: In edit mode, the EditItemTemplate element generates the text boxes where users can enter updated values for the Name and GroupName fields. Figure 4. Records Affected: At the end of the update process, the control displays the number of records affected by the update operation in a Label control. Note the Update and Cancel links in the right column in Edit mode. When you click on the Update link to save the changes back to the database, the code uses the OnItemUpdated event to display the number of records affected (see Figure 4). That completes the key features of ListView control. You've seen examples of using it to create a simple data-driven web page, and a more complex page that leverages the control's update functionality declaratively, by specifying appropriate edit and confirmation markup. Finally, you have seen how to handle events generated by the ListView control. As you can see, the ListView's extensible nature lets you customize the runtime behavior easily to suit your needs. Thiru Thangarathinam works at Intel Corporation in Chandler, Arizona. He's a Microsoft MVP who specializes in architecting, designing, and developing distributed enterprise-class applications using .NET-related technologies. He is the author of the books 'Professional ASP.NET 2.0 XML' and 'Professional ASP.NET 2.0 Databases' from Wrox press and has coauthored a number of books on .NET-related technologies. He is a frequent contributor to leading technology-related online publications.

1 comment:

  1. I’m not that much of a online гeader to be honeѕt but your blοgs really nice, κeеp
    it up! I'll go ahead and bookmark your website to come back in the future. Many thanks

    Feel free to visit my site ... rimmel

    ReplyDelete



Powered by Blogger.