Using the New ListView Control in ASP.NET 3.5

Using the New ListView Control in ASP.NET 3.5

ny 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 (

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

). 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:

<%# Eval("Name") %>
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 AdventureWorks 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:


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:


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.


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:


Next, in the ItemTemplate element, you specify the link users click to edit an item:

         ----      ----                  

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.



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.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as