Export (0) Print
Expand All

ListView Class

Updated: July 2008

Displays the values of a data source by using user-defined templates. The ListView control enables users to select, sort, delete, edit, and insert records.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web.Extensions (in System.Web.Extensions.dll)

[ToolboxBitmapAttribute(typeof(ListView), "ListView.ico")]
[ControlValuePropertyAttribute("SelectedValue")]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class ListView : DataBoundControl, INamingContainer, 
	IPageableItemContainer
<asp:ListView />

In this topic:

Introduction

The ListView control is used to display the values from a data source. It resembles the GridView control, except that it displays data by using user-defined templates instead of row fields. Creating your own templates gives you more flexibility in controlling how the data is displayed.

A Visual Studio project with source code is available to accompany this topic: Download.

The ListView control supports the following features:

  • Support for binding to data source controls such as SqlDataSource, LinqDataSource, and ObjectDataSource.

  • Customizable appearance through user-defined templates and styles.

  • Built-in sorting capabilities.

  • Built-in update and delete capabilities.

  • Built-in insert capabilities.

  • Support for paging capabilities by using a DataPager control.

  • Built-in item selection capabilities.

  • Programmatic access to the ListView object model to dynamically set properties, handle events, and so on.

  • Multiple key fields.

To learn about other data-bound controls that are available in ASP.NET, see ASP.NET Data-Bound Web Server Controls Overview.

Templates

In order for the ListView control to display content, you must create templates for different parts of the control. The LayoutTemplate and ItemTemplate are required. All other templates are optional.

However, you must create a template for the mode in which the control is configured. For example, a ListView control that supports inserting records must have an InsertItemTemplate template defined. The following table lists the templates that you can create for the ListView control.

Template type

Description

LayoutTemplate

The root template that defines a container object, such as a table, div, or span element, that will contain the content defined in the ItemTemplate or GroupTemplate template. It might also contain a DataPager object.

ItemTemplate

Defines the data-bound content to display for individual items.

ItemSeparatorTemplate

Defines the content to render between individual items.

GroupTemplate

Defines a container object, such as a table row (tr), div, or span element, that will contain the content defined in the ItemTemplate and EmptyItemTemplate templates. The number of items that are displayed in a group is specified by the GroupItemCount property.

GroupSeparatorTemplate

Defines the content to render between groups of items.

EmptyItemTemplate

Defines the content to render for an empty item when a GroupTemplate template is used. For example, if the GroupItemCount property is set to 5, and the total number of items returned from the data source is 8, the last group of data displayed by the ListView control will contain three items as specified by the ItemTemplate template, and two items as specified by the EmptyItemTemplate template.

EmptyDataTemplate

Defines the content to render if the data source returns no data.

SelectedItemTemplate

Defines the content to render for the selected data item to differentiate the selected item from other items.

AlternatingItemTemplate

Defines the content to render for alternating items to make it easier to distinguish between consecutive items.

EditItemTemplate

Defines the content to render when an item is being edited. The EditItemTemplate template is rendered in place of the ItemTemplate template for the data item that is being edited.

InsertItemTemplate

Defines the content to render to insert an item. The InsertItemTemplate template is rendered in place of an ItemTemplate template at either the start or at the end of the items that are displayed by the ListView control. You can specify where the InsertItemTemplate template is rendered by using the InsertItemPosition property of the ListView control.

To display the value of a field in a template such as ItemTemplate, you use a data-binding expression. For more information about data-binding expressions, see Data-Binding Expressions Overview.

To bind input controls in the EditItemTemplate and InsertItemTemplate templates to fields of a data source, you can use two-way binding expressions. This enables the ListView control to automatically extract the values of the input control for an update or insert operation. Two-way binding expressions also enable input controls in an EditItemTemplate to automatically display the original field values. For more information about two-way binding expressions, see Binding to Databases.

Binding to a Data Source

You can bind the ListView control to a data source control (such as SqlDataSource, LinqDataSource, ObjectDataSource, and so on) and to any data source that implements the System.Collections.IEnumerable interface (such as System.Data.DataView, System.Collections.ArrayList, or System.Collections.Hashtable). Use one of the following methods to bind the ListView control to the appropriate data source type:

  • To bind to a data source control, set the DataSourceID property of the ListView control to the ID value of the data source control. The ListView control automatically binds to the specified data source control and can take advantage of the data source control's capabilities to perform sorting, inserting, updating, deleting, and paging functionality. This is the preferred method to bind to data.

  • To bind to a data source that implements the System.Collections.IEnumerable interface, programmatically set the DataSource property of the ListView control to the data source, and then call the DataBind method. When you use this technique, the ListView control does not provide built-in sorting, updating, deleting, and paging functionality. You must provide this functionality by using the appropriate event.

For more information about data binding, see Accessing Data with ASP.NET.

NoteNote:

The ListView control can be used to display user input, which might include malicious client script. Check any information that is sent from a client for executable script, SQL statements, or other code before you display it in the application. We strongly recommend that values be HTML-encoded whenever possible before they are displayed in this control. ASP.NET provides an input request validation feature to help block script and HTML in user input. You can also use validation server controls to check user input. For more information, see Introduction to the Validation Controls.

Data Operations

When the ListView control is bound to a data source control, the ListView control can take advantage of the data source control's capabilities and provide automatic sort, insert, update, and delete functionality.

NoteNote:

The ListView control can provide support for sorting, inserting, updating, and deleting with other types of data sources. However, in order to implement these operations, you must create code in an appropriate event handler.

Because the ListView control uses templates, it does not provide a way to automatically generate buttons to perform update, delete, insert, sort, or select operations. You must manually include these buttons in the appropriate template. The ListView control recognizes certain buttons whose CommandName property is set to a specific value. The following table lists the buttons that the ListView control recognizes and their functions.

Button

CommandName value

Description

Cancel

"Cancel"

Cancels an edit or insert operation. Raises the ItemCanceling event.

Delete

"Delete"

Deletes the current record from the data source. Raises the ItemDeleted and ItemDeleting events.

Select

"Select"

Sets the SelectedIndex property to the DisplayIndex property value for the item. Renders the SelectedItemTemplate template for the item. Raises the SelectedIndexChanging and SelectedIndexChanged events.

Edit

"Edit"

Puts the item in edit mode. Renders the EditItemTemplate template for the item. Raises the ItemEditing event.

Insert

"Insert"

Inserts the bound values from the InsertItemTemplate template into the data source. Raises the ItemInserting and ItemInserted events.

Update

"Update"

Updates the current record in the data source with the bound values from the EditItemTemplate template. Raises the ItemUpdating and ItemUpdated events.

Sort

"Sort"

Sorts the columns listed in the CommandArgument property of the button. Raises the Sorting and Sorted events.

Unlike the Delete button (which deletes the current data item immediately), when the Edit button is clicked, the ListView control displays the current item in edit mode. In edit mode, the content that is contained in the EditItemTemplate property is displayed for the current data item. Typically, in the edit item template, the Edit button is replaced with an Update and a Cancel button. Input controls that are appropriate for the field's data type (such as a TextBox or CheckBox control) also usually display a field's value for a user to modify. Clicking the Update button updates the record in the data source, and clicking the Cancel button cancels the edit operation.

The insert functionality is enabled when the InsertItemPosition property is set to FirstItem or LastItem. This property defines where the InsertItemTemplate template is rendered for the insert item. The insert item template typically includes an Insert and a Cancel button, and empty input controls are displayed for users to enter the values for the new record. Clicking the Insert button inserts the record in the data source, and clicking the Cancel button clears all the fields.

Sorting

The ListView control enables users to sort the items by clicking the Sort button. Sort functionality is defined in the CommandArgument property of the button that contains the columns to be sorted.

Paging

Instead of displaying all the records from the data source at the same time, the ListView control can break the records into pages. To enable paging, associate a DataPager control with the ListView control. Then insert a DataPager control inside the LayoutTemplate template. Alternatively, if the DataPager control is outside the ListView control, set the PagedControlID property to the ID of the ListView control.

Events

The following table lists the events that are supported by the ListView control.

Event

Description

ItemCanceling

Occurs when the Cancel button (a button with its CommandName property set to "Cancel") is clicked, but before the ListView control cancels the insert or edit operation. This event is often used to stop the cancel operation.

ItemCommand

Occurs when a button is clicked in the ListView control. This event is often used to perform a custom task when a button is clicked in the control.

ItemCreated

Occurs when a new item is created in the ListView control. This event is often used to modify the content of an item when the item is created.

ItemDataBound

Occurs when a data item is bound to data in the ListView control. This event is often used to modify the content of an item when the item is bound to data.

ItemDeleted

Occurs when a Delete button (a button with its CommandName property set to "Delete") is clicked or the DeleteItem method is called, after the ListView control deletes the record from the data source. This event is often used to check the results of the delete operation.

ItemDeleting

Occurs when a Delete button (a button with its CommandName property set to "Delete") is clicked or the DeleteItem method is called, but before the ListView control deletes the record from the data source. This event is often used to confirm or cancel the delete operation.

ItemEditing

Occurs when an Edit button (a button with its CommandName property set to "Edit") is clicked, but before the ListView control enters edit mode. This event is often used to cancel the editing operation.

ItemInserted

Occurs when an Insert button (a button with its CommandName property set to "Insert") is clicked or the InsertNewItem method is called, after the ListView control inserts the new record from the data source. This event is often used to check the results of the insert operation.

ItemInserting

Occurs when an Insert button (a button with its CommandName property set to "Insert") is clicked or the InsertNewItem method is called, but before the ListView control inserts the record. This event is often used to cancel the insert operation or change or validate the values of the new item.

ItemUpdated

Occurs when an Update button (a button with its CommandName property set to "Update") is clicked or the UpdateItem method is called, after the ListView control updates the record. This event is often used to check the results of the update operation.

ItemUpdating

Occurs when an Update button (a button with its CommandName property set to "Update") is clicked or the UpdateItem method is called, but before the ListView control updates the record. This event is often used to cancel the updating operation or change or validate the values of the edited item.

LayoutCreated

Occurs when the LayoutTemplate template is created in a ListView control. This event is often used to perform a task after the template is created.

PagePropertiesChanged

Occurs when the page properties change, after the ListView control sets the new values.

PagePropertiesChanging

Occurs when the data-page properties change, but before the ListView control sets the new values.

SelectedIndexChanged

Occurs when a Select button (a button with its CommandName property set to "Select") is clicked, after the ListView control handles the select operation. This event is often used to perform a custom task after an item is selected in the control.

SelectedIndexChanging

Occurs when a Select button (a button with its CommandName property set to "Select") is clicked, but before the ListView control handles the select operation. This event is often used to cancel the select operation.

Sorted

Occurs when a Sort button (a button with its CommandName property set to "Sort") is clicked or the Sort method is called, after the ListView control handles the sort operation. This event is typically used to perform a custom task after a user clicks a Sort button and the data has been sorted.

Sorting

Occurs when a Sort button (a button with its CommandName property set to "Sort") is clicked or the Sort method is called, but before the ListView control handles the sort operation. This event is often used to cancel the sorting operation or to perform a custom sorting routine.

TopicLocation
Walkthrough: Displaying, Paging, and Sorting Data Using the ListView Web Server ControlBuilding ASP .NET Web Applications in Visual Studio

The following example shows how to use the ListView control to display records from a database by using an HTML table. The values are retrieved by using a LinqDataSource control.

<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>ListView Example</title>
  </head>
  <body>
    <form id="form1" runat="server">

      <h3>ListView Example</h3>

      <asp:ListView ID="VendorsListView"
        DataSourceID="VendorsDataSource"
        DataKeyNames="VendorID"
        runat="server">
        <LayoutTemplate>
          <table cellpadding="2" width="640px" border="1" ID="tbl1" runat="server">
            <tr runat="server" style="background-color: #98FB98">
              <th runat="server">ID</th>
              <th runat="server">Account Number</th>
              <th runat="server">Name</th>
              <th runat="server">Preferred Vendor</th>
            </tr>
            <tr runat="server" id="itemPlaceholder" />
          </table>
          <asp:DataPager ID="DataPager1" runat="server">
            <Fields>
              <asp:NumericPagerField />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td>
              <asp:Label ID="VendorIDLabel" runat="server" Text='<%# Eval("VendorID") %>' />
            </td>
            <td>
              <asp:Label ID="AccountNumberLabel" runat="server" Text='<%# Eval("AccountNumber") %>' />
            </td>
            <td>
              <asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' /></td>
            <td>
              <asp:CheckBox ID="PreferredCheckBox" runat="server" 
                Checked='<%# Eval("PreferredVendorStatus") %>' Enabled="False" />
            </td>
          </tr>
        </ItemTemplate>
      </asp:ListView>

      <!-- This example uses Microsoft SQL Server and connects   -->
      <!-- to the AdventureWorks sample database. Add a LINQ     -->
      <!-- to SQL class to the project to map to a table in      -->
      <!-- the database.                                         -->
      <asp:LinqDataSource ID="VendorsDataSource" runat="server" 
        ContextTypeName="AdventureWorksClassesDataContext" 
        Select="new (VendorID, AccountNumber, Name, PreferredVendorStatus)" 
        TableName="Vendors" Where="ActiveFlag == @ActiveFlag">
        <WhereParameters>
          <asp:Parameter DefaultValue="true" Name="ActiveFlag" Type="Boolean" />
        </WhereParameters>
      </asp:LinqDataSource>

    </form>
  </body>
</html>

The following example shows how to use the ListView control to display values in a flow layout by using the div element. The values are retrieved by using a SqlDataSource control.

<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>ListView Flow Layout Example</title>
    <style type="text/css">
      .plainBox {
          font-family: Verdana, Arial, sans-serif;
          font-size: 11px;
          background: #ffffff;
          border:1px solid #336666;
          }
    </style>
  </head>
  <body>
    <form id="form1" runat="server">

      <h3>ListView Flow Layout Example</h3>

      Select the color:
      <asp:DropDownList ID="ColorList" runat="server" 
        AutoPostBack="True" 
        DataSourceID="ColorDataSource" 
        DataTextField="Color" 
        DataValueField="Color">
      </asp:DropDownList><br /><br />

      <asp:ListView runat="server" ID="ProductListView"
        DataSourceID="ProductsDataSource"
        DataKeyNames="ProductID">
        <LayoutTemplate>
          <div runat="server" id="lstProducts">
            <div runat="server" id="itemPlaceholder" />
          </div>
          <asp:DataPager runat="server" PageSize="5" >
            <Fields>
              <asp:NextPreviousPagerField 
                ButtonType="Button"
                ShowFirstPageButton="True" 
                ShowLastPageButton="True" />
            </Fields>
          </asp:DataPager>
        </LayoutTemplate>
        <ItemTemplate>
          <asp:Image ID="ProductImage" runat="server"
            ImageUrl='<%# "~/images/thumbnails/" + Eval("ThumbnailPhotoFileName") %>' />	        
          <div class="plainBox" runat="server">
            <asp:HyperLink ID="ProductLink" runat="server" Text='<%# Eval("Name") %>' 
              NavigateUrl='<%# "ProductDetails.aspx?productID=" + Eval("ProductID") %>' />
            <br /><br />
            <b>Price:</b> 
            <asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("ListPrice", "{0:c}")%>' /> <br />
          </div>
          <br />
        </ItemTemplate>
      </asp:ListView>

      <!-- This example uses Microsoft SQL Server and connects      -->
      <!-- to the AdventureWorks sample database. Use an ASP.NET    -->
      <!-- expression to retrieve the connection string value       -->
      <!-- from the Web.config file.                                -->
      <asp:SqlDataSource ID="ProductsDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"            	        
        SelectCommand="SELECT P.ProductID, P.Name, P.Color, P.ListPrice, 
          PF.ThumbnailPhotoFileName, P.Size
          FROM Production.Product AS P 
          INNER JOIN Production.ProductProductPhoto AS PPF ON P.ProductID = PPF.ProductID 
          INNER JOIN Production.ProductPhoto AS PF ON PPF.ProductPhotoID = PF.ProductPhotoID
          WHERE P.Color = @Color" >
        <SelectParameters>
          <asp:ControlParameter ControlID="ColorList" Name="Color" 
            PropertyName="SelectedValue" />
        </SelectParameters>
      </asp:SqlDataSource>

      <asp:SqlDataSource ID="ColorDataSource" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>" 
        SelectCommand="SELECT DISTINCT Color FROM Production.Product">
      </asp:SqlDataSource>

    </form>
  </body>
</html>

The following example shows how to use the ListView control to insert, delete, and update records.

Security noteSecurity Note:

This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<%@ Page language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
  <head id="Head1" runat="server">
    <title>ListView Example</title>
    <style type="text/css">
        .EditItem { background-color:#8FBC8F;}
        .SelectedItem {	background-color:#9ACD32; }
        .InsertItem { background-color:#FFFACD;}
    </style>
  </head>
  <body>
    <form id="form1" runat="server">

      <h3>ListView Example</h3>

      <h5>Departments</h5>

      <asp:ListView ID="DepartmentsListView" 
        DataSourceID="DepartmentsDataSource" 
        DataKeyNames="DepartmentID"
        ConvertEmptyStringToNull="true"
        InsertItemPosition="LastItem"
        runat="server">
        <LayoutTemplate>
          <table cellpadding="2" runat="server" id="tblDepartments" width="640px" cellspacing="0">
            <tr runat="server" id="itemPlaceholder" />
          </table>
        </LayoutTemplate>
        <ItemTemplate>
          <tr runat="server">
            <td>
              <asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select" />
              <asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
            </td>
            <td>
              <asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
            </td>
            <td>
              <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
            </td>
            <td>
              <asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
            </td>
          </tr>
        </ItemTemplate>
        <SelectedItemTemplate>
          <tr class="SelectedItem" runat="server">
            <td>
              <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" />
              <asp:Button ID="EditButton" runat="server" Text="Edit" CommandName="Edit" />
            </td>
            <td>
              <asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
            </td>
            <td>
              <asp:Label ID="NameLabel" runat="server" Text='<%#Eval("Name") %>' />
            </td>
            <td>
              <asp:Label ID="GroupNameLabel" runat="server" Text='<%#Eval("GroupName") %>' />
            </td>
          </tr>
        </SelectedItemTemplate>
        <EditItemTemplate>
          <tr class="EditItem">
            <td>
              <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
              <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
            </td>
            <td>
              <b>ID</b><br />
              <asp:Label ID="IDLabel" runat="server" Text='<%#Eval("DepartmentID") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox" 
                Text="Name" Font-Bold="true"/><br />
              <asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' />
            </td>
            <td>
              <asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox" 
                Text="Group Name" Font-Bold="true" /><br />
              <asp:TextBox ID="GroupNameTextBox" runat="server" 
                Width="200px"
                Text='<%#Bind("GroupName") %>' />
              <br />
            </td>
          </tr>
        </EditItemTemplate>
        <InsertItemTemplate>
          <tr class="InsertItem">
            <td colspan="2">
              <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
              <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
            </td>
            <td>
              <asp:Label runat="server" ID="NameLabel" AssociatedControlID="NameTextBox" 
                Text="Name" Font-Bold="true"/><br />
              <asp:TextBox ID="NameTextBox" runat="server" Text='<%#Bind("Name") %>' /><br />
            </td>
            <td>
              <asp:Label runat="server" ID="GroupNameLabel" AssociatedControlID="GroupNameTextBox" 
                Text="Group Name" Font-Bold="true" /><br />                
              <asp:TextBox ID="GroupNameTextBox" runat="server" Text='<%#Bind("GroupName") %>' />
            </td>
          </tr>
        </InsertItemTemplate>
      </asp:ListView>

      <!-- This example uses Microsoft SQL Server and connects      -->
      <!-- to the AdventureWorks sample database. Use an ASP.NET    -->
      <!-- expression to retrieve the connection string value       -->
      <!-- from the Web.config file.                                -->            
      <asp:SqlDataSource ID="DepartmentsDataSource" runat="server" 
            ConnectionString="<%$ ConnectionStrings:AdventureWorks_DataConnectionString %>"
            SelectCommand="SELECT DepartmentID, Name, GroupName FROM HumanResources.Department"
            UpdateCommand="UPDATE HumanResources.Department 
                SET Name = @Name, GroupName = @GroupName WHERE (DepartmentID = @DepartmentID)"            
	        DeleteCommand="DELETE FROM HumanResources.Department 
	            WHERE (DepartmentID = @DepartmentID)" 
	        InsertCommand="INSERT INTO HumanResources.Department(Name, GroupName) 
	            VALUES (@Name, @GroupName)">
      </asp:SqlDataSource>

    </form>
  </body>
</html>

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5

Date

History

Reason

July 2008

Added new members: EnableModelValidation property, SelectedPersistedDataKey property, IPersistedSelector.DataKey property.

SP1 feature change.

Community Additions

ADD
Show:
© 2014 Microsoft