ערוך

שתף באמצעות


ListView Class

Definition

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.

public ref class ListView : System::Web::UI::WebControls::DataBoundControl, System::Web::UI::INamingContainer, System::Web::UI::WebControls::IPageableItemContainer, System::Web::UI::WebControls::IPersistedSelector
public ref class ListView : System::Web::UI::WebControls::DataBoundControl, System::Web::UI::IDataKeysControl, System::Web::UI::INamingContainer, System::Web::UI::WebControls::IDataBoundListControl, System::Web::UI::WebControls::IPageableItemContainer, System::Web::UI::WebControls::IPersistedSelector
[System.Drawing.ToolboxBitmap(typeof(System.Web.UI.WebControls.ListView), "ListView.ico")]
[System.Web.UI.ControlValueProperty("SelectedValue")]
public class ListView : System.Web.UI.WebControls.DataBoundControl, System.Web.UI.INamingContainer, System.Web.UI.WebControls.IPageableItemContainer, System.Web.UI.WebControls.IPersistedSelector
[System.Web.UI.ControlValueProperty("SelectedValue")]
[System.Drawing.ToolboxBitmap(typeof(System.Web.UI.WebControls.ListView), "ListView.bmp")]
public class ListView : System.Web.UI.WebControls.DataBoundControl, System.Web.UI.IDataKeysControl, System.Web.UI.INamingContainer, System.Web.UI.WebControls.IDataBoundListControl, System.Web.UI.WebControls.IPageableItemContainer, System.Web.UI.WebControls.IPersistedSelector
[<System.Drawing.ToolboxBitmap(typeof(System.Web.UI.WebControls.ListView), "ListView.ico")>]
[<System.Web.UI.ControlValueProperty("SelectedValue")>]
type ListView = class
    inherit DataBoundControl
    interface INamingContainer
    interface IPageableItemContainer
    interface IPersistedSelector
[<System.Web.UI.ControlValueProperty("SelectedValue")>]
[<System.Drawing.ToolboxBitmap(typeof(System.Web.UI.WebControls.ListView), "ListView.bmp")>]
type ListView = class
    inherit DataBoundControl
    interface INamingContainer
    interface IPageableItemContainer
    interface IPersistedSelector
    interface IDataKeysControl
    interface IDataBoundListControl
    interface IDataBoundControl
Public Class ListView
Inherits DataBoundControl
Implements INamingContainer, IPageableItemContainer, IPersistedSelector
Public Class ListView
Inherits DataBoundControl
Implements IDataBoundListControl, IDataKeysControl, INamingContainer, IPageableItemContainer, IPersistedSelector
Inheritance
Attributes
Implements

Examples

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>
<%@ Page language="VB" %>
    
<!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>
<%@ Page language="VB" %>
    
<!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 ID="DataPager1" 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.

Important

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>
<%@ Page language="VB" %>
    
<!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>

Remarks

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 Data-Bound Web Server Controls.

Templates

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

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 the SqlDataSource control or ObjectDataSource control) or to any data source collection that implements the System.Collections.IEnumerable interface, such as System.Data.DataView, System.Collections.ArrayList, System.Collections.Generic.List<T>, or other collection types. 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 ASP.NET Data Access Content Map.

Note

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.

Note

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.

Declarative Syntax

<asp:ListView
    ConvertEmptyStringToNull="True|False"
    DataKeyNames="string"
    DataMember="string"
    DataSource="string"
    DataSourceID="string"
    EditIndex="integer"
    Enabled="True|False"
    EnableTheming="True|False"
    EnableViewState="True|False"
    GroupPlaceholderID="string"
    GroupItemCount="integer"
    ID="string"
    InsertItemPosition="None|FirstItem|LastItem"
    ItemPlaceholderID="string"
    OnDataBinding="DataBinding event handler"
    OnDataBound="DataBound event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnItemCanceling="ItemCanceling event handler"
    OnItemCommand="ItemCommand event handler"
    OnItemCreated="ItemCreated event handler"
    OnItemDataBound="ItemDataBound event handler"
    OnItemDeleted="ItemDeleted event handler"
    OnItemDeleting="ItemDeleting event handler"
    OnItemEditing="ItemEditing event handler"
    OnItemInserted="ItemInserted event handler"
    OnItemInserting="ItemInserting event handler"
    OnItemUpdated="ItemUpdated event handler"
    OnItemUpdating="ItemUpdating event handler"
    OnLayoutCreated="LayoutCreated event handler"
    OnLoad="Load event handler"
    OnPagePropertiesChanged="PagePropertiesChanged event handler"
    OnPagePropertiesChanging="PagePropertiesChanging event handler"
    OnPreRender="PreRender event handler"
    OnSelectedIndexChanged="SelectedIndexChanged event handler"
    OnSelectedIndexChanging="SelectedIndexChanging event handler"
    OnSorted="Sorted event handler"
    OnSorting="Sorting event handler"
    OnUnload="Unload event handler"
    runat="server"
    SelectedIndex="integer"
    SkinID="string"
    Style="string"
    Visible="True|False"
>
        <AlternatingItemTemplate>
            <!-- child controls -->
        </AlternatingItemTemplate>
        <EditItemTemplate>
            <!-- child controls -->
        </EditItemTemplate>
        <EmptyDataTemplate>
            <!-- child controls -->
        </EmptyDataTemplate>
        <EmptyItemTemplate>
            <!-- child controls -->
        </EmptyItemTemplate>
        <GroupSeparatorTemplate>
            <!-- child controls -->
        </GroupSeparatorTemplate>
        <GroupTemplate>
            <!-- child controls -->
        </GroupTemplate>
        <InsertItemTemplate>
            <!-- child controls -->
        </InsertItemTemplate>
        <ItemSeparatorTemplate>
            <!-- child controls -->
        </ItemSeparatorTemplate>
        <ItemTemplate>
            <!-- child controls -->
        </ItemTemplate>
        <LayoutTemplate>
                <!-- child controls -->
        </LayoutTemplate>
        <SelectedItemTemplate>
            <!-- child controls -->
        </SelectedItemTemplate>
</asp:ListView>

Constructors

ListView()

Initializes a new instance of the ListView class.

Properties

AccessKey

Overrides the AccessKey property. Setting this property is not supported by the ListView control.

Adapter

Gets the browser-specific adapter for the control.

(Inherited from Control)
AlternatingItemTemplate

Gets or sets the custom content for the alternating data item in a ListView control.

AppRelativeTemplateSourceDirectory

Gets or sets the application-relative virtual directory of the Page or UserControl object that contains this control.

(Inherited from Control)
Attributes

Gets the collection of arbitrary attributes (for rendering only) that do not correspond to properties on the control.

(Inherited from WebControl)
BackColor

Overrides the BackColor property. Setting this property is not supported by the ListView control.

BindingContainer

Gets the control that contains this control's data binding.

(Inherited from Control)
BorderColor

Overrides the BorderColor property. Setting this property is not supported by the ListView control.

BorderStyle

Overrides the BorderStyle property. Setting this property is not supported by the ListView control.

BorderWidth

Overrides the BorderWidth property. Setting this property is not supported by the ListView control.

ChildControlsCreated

Gets a value that indicates whether the server control's child controls have been created.

(Inherited from Control)
ClientID

Gets the control ID for HTML markup that is generated by ASP.NET.

(Inherited from Control)
ClientIDMode

Gets or sets the algorithm that is used to generate the value of the ClientID property.

(Inherited from Control)
ClientIDRowSuffix

Gets or sets the name of the data field whose value is used to uniquely identify each data row of a ListView control when the ClientIDMode property is set to Predictable.

ClientIDRowSuffixDataKeys

Gets the data values that are used to uniquely identify each instance of a data-bound control when ASP.NET generates the ClientID value.

ClientIDSeparator

Gets a character value representing the separator character used in the ClientID property.

(Inherited from Control)
Context

Gets the HttpContext object associated with the server control for the current Web request.

(Inherited from Control)
Controls

Gets a ControlCollection object that represents the child controls of the ListView control.

ControlStyle

Gets the style of the Web server control. This property is used primarily by control developers.

(Inherited from WebControl)
ControlStyleCreated

Gets a value indicating whether a Style object has been created for the ControlStyle property. This property is primarily used by control developers.

(Inherited from WebControl)
ConvertEmptyStringToNull

Gets or sets a value that indicates whether empty string values ("") are automatically converted to null values when the data field is updated in the data source.

CssClass

Overrides the CssClass property. Setting this property is not supported by the ListView control.

DataItemContainer

Gets a reference to the naming container if the naming container implements IDataItemContainer.

(Inherited from Control)
DataKeyNames

Gets or sets an array that contains the names of the primary key fields for the items displayed in a ListView control.

DataKeys

Gets a collection of DataKey objects that represent the data-key value for each item in a ListView control.

DataKeysContainer

Gets a reference to the naming container if the naming container implements IDataKeysControl.

(Inherited from Control)
DataMember

Gets or sets the name of the list of data that the data-bound control binds to, in cases where the data source contains more than one distinct list of data items.

(Inherited from DataBoundControl)
DataSource

Gets or sets the object from which the data-bound control retrieves its list of data items.

(Inherited from BaseDataBoundControl)
DataSourceID

Gets or sets the ID of the control from which the data-bound control retrieves its list of data items.

(Inherited from DataBoundControl)
DataSourceObject

Gets an object that implements the IDataSource interface, which provides access to the object's data content.

(Inherited from DataBoundControl)
DeleteMethod

Gets or sets the name of the method to call in order to delete data.

DesignMode

Gets a value indicating whether a control is being used on a design surface.

(Inherited from Control)
EditIndex

Gets or sets the index of the item being edited.

EditItem

Gets the item that is in edit mode in a ListView control.

EditItemTemplate

Gets or sets the custom content for the item in edit mode.

EmptyDataTemplate

Gets or sets the user-defined content for the empty template that is rendered when a ListView control is bound to a data source that does not contain any records.

EmptyItemTemplate

Gets or sets the user-defined content for the empty item that is rendered in a ListView control when there are no more data items to display in the last row of the current data page.

Enabled

Gets or sets a value indicating whether the Web server control is enabled.

(Inherited from WebControl)
EnableModelValidation

Gets or sets a value that indicates whether a validator control will handle exceptions that occur during insert or update operations.

EnablePersistedSelection

Gets or sets a value that indicates whether row selection persists when a user pages through data in a data-bound control.

EnableTheming

Gets or sets a value indicating whether themes apply to this control.

(Inherited from WebControl)
EnableViewState

Gets or sets a value indicating whether the server control persists its view state, and the view state of any child controls it contains, to the requesting client.

(Inherited from Control)
Events

Gets a list of event handler delegates for the control. This property is read-only.

(Inherited from Control)
Font

Overrides the Font property. This property is not supported by the ListView control.

ForeColor

Overrides the ForeColor property. Setting this property is not supported by the ListView control.

GroupItemCount

Gets or sets the number of items to display per group in a ListView control.

GroupPlaceholderID

Gets or sets the ID for the group placeholder in a ListView control.

GroupSeparatorTemplate

Gets or sets the user-defined content for the separator between groups in a ListView control.

GroupTemplate

Gets or sets the user-defined content for the group container in a ListView control.

HasAttributes

Gets a value indicating whether the control has attributes set.

(Inherited from WebControl)
HasChildViewState

Gets a value indicating whether the current server control's child controls have any saved view-state settings.

(Inherited from Control)
Height

Overrides the Height property. Setting this property is not supported by the ListView control.

ID

Gets or sets the programmatic identifier assigned to the server control.

(Inherited from Control)
IdSeparator

Gets the character used to separate control identifiers.

(Inherited from Control)
Initialized

Gets a value indicating whether the data-bound control has been initialized.

(Inherited from BaseDataBoundControl)
InsertItem

Gets the insert item of a ListView control.

InsertItemPosition

Gets or sets the location of the InsertItemTemplate template when it is rendered as part of the ListView control.

InsertItemTemplate

Gets or sets the custom content for an insert item in the ListView control.

InsertMethod

Gets or sets the name of the method to call in order to insert data.

IsBoundUsingDataSourceID

Gets a value indicating whether the DataSourceID property is set.

(Inherited from BaseDataBoundControl)
IsChildControlStateCleared

Gets a value indicating whether controls contained within this control have control state.

(Inherited from Control)
IsDataBindingAutomatic

Gets a value that indicates whether data binding is automatic.

(Inherited from BaseDataBoundControl)
IsEnabled

Gets a value indicating whether the control is enabled.

(Inherited from WebControl)
IsTrackingViewState

Gets a value that indicates whether the server control is saving changes to its view state.

(Inherited from Control)
IsUsingModelBinders

Gets a value that indicates whether model binding is in use.

IsUsingModelBinders

Gets a value that indicates whether model binding is in use.

(Inherited from DataBoundControl)
IsViewStateEnabled

Gets a value indicating whether view state is enabled for this control.

(Inherited from Control)
ItemPlaceholderID

Gets or sets the ID for the item placeholder in a ListView control.

Items

Gets a collection of ListViewDataItem objects that represent the data items of the current page of data in a ListView control.

ItemSeparatorTemplate

Gets or sets the custom content for the separator between the items in a ListView control.

ItemTemplate

Gets or sets the custom content for the data item in a ListView control.

ItemType

Gets or sets the name of the data item type for strongly typed data binding.

(Inherited from DataBoundControl)
LayoutTemplate

Gets or sets the custom content for the root container in a ListView control.

LoadViewStateByID

Gets a value indicating whether the control participates in loading its view state by ID instead of index.

(Inherited from Control)
MaximumRows

Gets the maximum number of items to display on a single page of the ListView control.

NamingContainer

Gets a reference to the server control's naming container, which creates a unique namespace for differentiating between server controls with the same ID property value.

(Inherited from Control)
Page

Gets a reference to the Page instance that contains the server control.

(Inherited from Control)
Parent

Gets a reference to the server control's parent control in the page control hierarchy.

(Inherited from Control)
RenderingCompatibility

Gets a value that specifies the ASP.NET version that rendered HTML will be compatible with.

(Inherited from Control)
RequiresDataBinding

Gets or sets a value indicating whether the DataBind() method should be called.

(Inherited from BaseDataBoundControl)
SelectArguments

Gets a DataSourceSelectArguments object that the data-bound control uses when retrieving data from a data source control.

(Inherited from DataBoundControl)
SelectedDataKey

Gets the data-key value for the selected item in a ListView control.

SelectedIndex

Gets or sets the index of the selected item in a ListView control.

SelectedItemTemplate

Gets or sets the custom content for the selected item in a ListView control.

SelectedPersistedDataKey

Gets or sets the data-key value for the persisted selected item in a data-bound control.

SelectedValue

Gets the data-key value of the selected item in a ListView control.

SelectMethod

The name of the method to call in order to read data.

(Inherited from DataBoundControl)
Site

Gets information about the container that hosts the current control when rendered on a design surface.

(Inherited from Control)
SkinID

Gets or sets the skin to apply to the control.

(Inherited from WebControl)
SortDirection

Gets the sort direction of the field or fields that are being sorted.

SortExpression

Gets the sort expression that is associated with the field or fields that are being sorted.

StartRowIndex

Gets the index of the first record that is displayed on a page of data in the ListView control.

Style

Gets a collection of text attributes that will be rendered as a style attribute on the outer tag of the Web server control.

(Inherited from WebControl)
SupportsDisabledAttribute

Gets a value that indicates whether the control should set the disabled attribute of the rendered HTML element to "disabled" when the control's IsEnabled property is false.

(Inherited from BaseDataBoundControl)
TabIndex

Overrides the TabIndex property. Setting this property is not supported by the ListView control.

TagKey

Gets the HtmlTextWriterTag value that corresponds to this Web server control. This property is used primarily by control developers.

(Inherited from WebControl)
TagName

Gets the name of the control tag. This property is used primarily by control developers.

(Inherited from WebControl)
TemplateControl

Gets or sets a reference to the template that contains this control.

(Inherited from Control)
TemplateSourceDirectory

Gets the virtual directory of the Page or UserControl that contains the current server control.

(Inherited from Control)
ToolTip

Overrides the ToolTip property. Setting this property is not supported by the ListView control.

UniqueID

Gets the unique, hierarchically qualified identifier for the server control.

(Inherited from Control)
UpdateMethod

Gets or sets the name of the method to call in order to update data.

ValidateRequestMode

Gets or sets a value that indicates whether the control checks client input from the browser for potentially dangerous values.

(Inherited from Control)
ViewState

Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.

(Inherited from Control)
ViewStateIgnoresCase

Gets a value that indicates whether the StateBag object is case-insensitive.

(Inherited from Control)
ViewStateMode

Gets or sets the view-state mode of this control.

(Inherited from Control)
Visible

Gets or sets a value that indicates whether a server control is rendered as UI on the page.

(Inherited from Control)
Width

Overrides the Width property. Setting this property is not supported by the ListView control.

Methods

AddAttributesToRender(HtmlTextWriter)

Adds HTML attributes and styles that need to be rendered to the specified HtmlTextWriterTag. This method is used primarily by control developers.

(Inherited from WebControl)
AddControlToContainer(Control, Control, Int32)

Adds the specified control to the specified container.

AddedControl(Control, Int32)

Called after a child control is added to the Controls collection of the Control object.

(Inherited from Control)
AddParsedSubObject(Object)

Notifies the server control that an element, either XML or HTML, was parsed, and adds the element to the server control's ControlCollection object.

(Inherited from Control)
ApplyStyle(Style)

Copies any nonblank elements of the specified style to the Web control, overwriting any existing style elements of the control. This method is primarily used by control developers.

(Inherited from WebControl)
ApplyStyleSheetSkin(Page)

Applies the style properties defined in the page style sheet to the control.

(Inherited from Control)
BeginRenderTracing(TextWriter, Object)

Begins design-time tracing of rendering data.

(Inherited from Control)
BuildProfileTree(String, Boolean)

Gathers information about the server control and delivers it to the Trace property to be displayed when tracing is enabled for the page.

(Inherited from Control)
ClearCachedClientID()

Sets the cached ClientID value to null.

(Inherited from Control)
ClearChildControlState()

Deletes the control-state information for the server control's child controls.

(Inherited from Control)
ClearChildState()

Deletes the view-state and control-state information for all the server control's child controls.

(Inherited from Control)
ClearChildViewState()

Deletes the view-state information for all the server control's child controls.

(Inherited from Control)
ClearEffectiveClientIDMode()

Sets the ClientIDMode property of the current control instance and of any child controls to Inherit.

(Inherited from Control)
ConfirmInitState()

Sets the initialized state of the data-bound control.

(Inherited from BaseDataBoundControl)
CopyBaseAttributes(WebControl)

Copies the properties not encapsulated by the Style object from the specified Web server control to the Web server control that this method is called from. This method is used primarily by control developers.

(Inherited from WebControl)
CreateChildControls()

Creates the control hierarchy that is used to render the ListView control, based on the values that are stored in view state.

CreateChildControls(IEnumerable, Boolean)

Creates the control hierarchy that is used to render the ListView control by using the specified data source.

CreateControlCollection()

Creates a new ControlCollection object to hold the child controls (both literal and server) of the server control.

(Inherited from Control)
CreateControlStyle()

Creates the default style for the control.

CreateDataItem(Int32, Int32)

Creates a data item in the ListView control.

CreateDataSourceSelectArguments()

Creates the DataSourceSelectArguments object that contains the arguments that are passed to the data source.

CreateEmptyDataItem()

Creates the EmptyDataTemplate template in the ListView control.

CreateEmptyItem()

Creates an empty item in the ListView control.

CreateInsertItem()

Creates an insert item in the ListView control.

CreateItem(ListViewItemType)

Creates a ListViewItem object with the specified type.

CreateItemsInGroups(ListViewPagedDataSource, Boolean, InsertItemPosition, ArrayList)

Creates the ListView control hierarchy in groups.

CreateItemsWithoutGroups(ListViewPagedDataSource, Boolean, InsertItemPosition, ArrayList)

Creates the ListView control hierarchy without groups.

CreateLayoutTemplate()

Creates the root container in the ListView control.

CreateSuffixArrayList(ListViewPagedDataSource, ArrayList)

Creates an array of suffixes for ASP.NET to use when it generates the ClientID value.

DataBind()

Binds a data source to the invoked server control and all its child controls.

(Inherited from BaseDataBoundControl)
DataBind(Boolean)

Binds a data source to the invoked server control and all its child controls with an option to raise the DataBinding event.

(Inherited from Control)
DataBindChildren()

Binds a data source to the server control's child controls.

(Inherited from Control)
DeleteItem(Int32)

Deletes the record at the specified index from the data source.

Dispose()

Enables a server control to perform final clean up before it is released from memory.

(Inherited from Control)
EndRenderTracing(TextWriter, Object)

Ends design-time tracing of rendering data.

(Inherited from Control)
EnsureChildControls()

Determines whether the server control contains child controls. If it does not, it creates child controls.

(Inherited from Control)
EnsureDataBound()

Calls the DataBind() method if the DataSourceID property is set and the data-bound control is marked to require binding.

(Inherited from BaseDataBoundControl)
EnsureID()

Creates an identifier for controls that do not have an identifier assigned.

(Inherited from Control)
EnsureLayoutTemplate()

Ensures that the LayoutTemplate content is correctly created in the ListView control.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
ExtractItemValues(IOrderedDictionary, ListViewItem, Boolean)

Retrieves the values of each field that is declared in the specified item, and stores them in the specified IOrderedDictionary object.

FindControl(String)

Searches the current naming container for a server control with the specified id parameter.

(Inherited from Control)
FindControl(String, Int32)

Searches the current naming container for a server control with the specified id and an integer, specified in the pathOffset parameter, which aids in the search. You should not override this version of the FindControl method.

(Inherited from Control)
FindPlaceholder(String, Control)

Searches the specified container for a control that has the specified identifier.

Focus()

Sets input focus to a control.

(Inherited from Control)
GetData()

Retrieves a DataSourceView object that the data-bound control uses to perform data operations.

(Inherited from DataBoundControl)
GetDataSource()

Retrieves the IDataSource interface that the data-bound control is associated with, if any.

(Inherited from DataBoundControl)
GetDesignModeState()

Gets design-time data for a control.

(Inherited from Control)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetRouteUrl(Object)

Gets the URL that corresponds to a set of route parameters.

(Inherited from Control)
GetRouteUrl(RouteValueDictionary)

Gets the URL that corresponds to a set of route parameters.

(Inherited from Control)
GetRouteUrl(String, Object)

Gets the URL that corresponds to a set of route parameters and a route name.

(Inherited from Control)
GetRouteUrl(String, RouteValueDictionary)

Gets the URL that corresponds to a set of route parameters and a route name.

(Inherited from Control)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
GetUniqueIDRelativeTo(Control)

Returns the prefixed portion of the UniqueID property of the specified control.

(Inherited from Control)
HasControls()

Determines if the server control contains any child controls.

(Inherited from Control)
HasEvents()

Returns a value indicating whether events are registered for the control or any child controls.

(Inherited from Control)
InsertNewItem(Boolean)

Inserts the current record in the data source.

InstantiateEmptyDataTemplate(Control)

Populates the specified Control object by using the child controls that are contained in the EmptyDataTemplate template.

InstantiateEmptyItemTemplate(Control)

Populates the specified Control object by using the child controls that are contained in the EmptyItemTemplate template.

InstantiateGroupSeparatorTemplate(Control)

Populates the specified Control object by using the child controls that are contained in the GroupSeparatorTemplate template.

InstantiateGroupTemplate(Control)

Populates the specified Control object by using the child controls that are contained in the GroupTemplate template.

InstantiateInsertItemTemplate(Control)

Populates the specified Control object by using the child controls that are contained in the InsertItemTemplate template.

InstantiateItemSeparatorTemplate(Control)

Populates the specified Control object by using the child controls that are contained in the ItemSeparatorTemplate template.

InstantiateItemTemplate(Control, Int32)

Populates the specified Control object by using child controls from one of the ListView control templates.

IsLiteralContent()

Determines if the server control holds only literal content.

(Inherited from Control)
LoadControlState(Object)

Loads the state of the properties in the ListView control that must be persisted, even when the EnableViewState property is set to false.

LoadViewState(Object)

Loads the previously saved view state of the ListView control.

MapPathSecure(String)

Retrieves the physical path that a virtual path, either absolute or relative, maps to.

(Inherited from Control)
MarkAsDataBound()

Sets the state of the control in view state as successfully bound to data.

(Inherited from DataBoundControl)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MergeStyle(Style)

Copies any nonblank elements of the specified style to the Web control, but will not overwrite any existing style elements of the control. This method is used primarily by control developers.

(Inherited from WebControl)
OnBubbleEvent(Object, EventArgs)

Determines whether an event for the ListView control should be handled.

OnCreatingModelDataSource(CreatingModelDataSourceEventArgs)

Raises the CreatingModelDataSource event.

(Inherited from DataBoundControl)
OnDataBinding(EventArgs)

Raises the DataBinding event.

(Inherited from Control)
OnDataBound(EventArgs)

Raises the DataBound event.

(Inherited from BaseDataBoundControl)
OnDataPropertyChanged()

Rebinds the data-bound control to its data after one of the base data source identification properties changes.

(Inherited from DataBoundControl)
OnDataSourceViewChanged(Object, EventArgs)

Raises the DataSourceViewChanged event.

(Inherited from DataBoundControl)
OnInit(EventArgs)

Raises the Init event.

OnItemCanceling(ListViewCancelEventArgs)

Raises the ItemCanceling event.

OnItemCommand(ListViewCommandEventArgs)

Raises the ItemCommand event.

OnItemCreated(ListViewItemEventArgs)

Raises the ItemCreated event.

OnItemDataBound(ListViewItemEventArgs)

Raises the ItemDataBound event.

OnItemDeleted(ListViewDeletedEventArgs)

Raises the ItemDeleted event.

OnItemDeleting(ListViewDeleteEventArgs)

Raises the ItemDeleting event.

OnItemEditing(ListViewEditEventArgs)

Raises the ItemEditing event.

OnItemInserted(ListViewInsertedEventArgs)

Raises the ItemInserted event.

OnItemInserting(ListViewInsertEventArgs)

Raises the ItemInserting event.

OnItemUpdated(ListViewUpdatedEventArgs)

Raises the ItemUpdated event.

OnItemUpdating(ListViewUpdateEventArgs)

Raises the ItemUpdating event.

OnLayoutCreated(EventArgs)

Raises the LayoutCreated event.

OnLoad(EventArgs)

Handles the Load event.

(Inherited from DataBoundControl)
OnPagePreLoad(Object, EventArgs)

Sets the initialized state of the data-bound control before the control is loaded.

(Inherited from DataBoundControl)
OnPagePropertiesChanged(EventArgs)

Raises the PagePropertiesChanged event.

OnPagePropertiesChanging(PagePropertiesChangingEventArgs)

Raises the PagePropertiesChanging event.

OnPreRender(EventArgs)

Handles the PreRender event.

(Inherited from BaseDataBoundControl)
OnSelectedIndexChanged(EventArgs)

Raises the SelectedIndexChanged event.

OnSelectedIndexChanging(ListViewSelectEventArgs)

Raises the SelectedIndexChanging event.

OnSorted(EventArgs)

Raises the Sorted event.

OnSorting(ListViewSortEventArgs)

Raises the Sorting event.

OnTotalRowCountAvailable(PageEventArgs)

Raises the IPageableItemContainer.TotalRowCountAvailable event.

OnUnload(EventArgs)

Raises the Unload event.

(Inherited from Control)
OpenFile(String)

Gets a Stream used to read a file.

(Inherited from Control)
PerformDataBinding(IEnumerable)

Binds the ListView control to the specified data source.

PerformSelect()

Retrieves data from the associated data source.

RaiseBubbleEvent(Object, EventArgs)

Assigns any sources of the event and its information to the control's parent.

(Inherited from Control)
RemovedControl(Control)

Called after a child control is removed from the Controls collection of the Control object.

(Inherited from Control)
RemoveItems()

Deletes all child controls in an item or group container of the ListView control.

Render(HtmlTextWriter)

Renders the Web server control content to the client's browser by using the specified HtmlTextWriter object.

RenderBeginTag(HtmlTextWriter)

Renders the HTML opening tag of the control to the specified writer. This method is used primarily by control developers.

(Inherited from WebControl)
RenderChildren(HtmlTextWriter)

Outputs the content of a server control's children to a provided HtmlTextWriter object, which writes the content to be rendered on the client.

(Inherited from Control)
RenderContents(HtmlTextWriter)

Renders the contents of the control to the specified writer. This method is used primarily by control developers.

(Inherited from WebControl)
RenderControl(HtmlTextWriter)

Outputs server control content to a provided HtmlTextWriter object and stores tracing information about the control if tracing is enabled.

(Inherited from Control)
RenderControl(HtmlTextWriter, ControlAdapter)

Outputs server control content to a provided HtmlTextWriter object using a provided ControlAdapter object.

(Inherited from Control)
RenderEndTag(HtmlTextWriter)

Renders the HTML closing tag of the control into the specified writer. This method is used primarily by control developers.

(Inherited from WebControl)
ResolveAdapter()

Gets the control adapter responsible for rendering the specified control.

(Inherited from Control)
ResolveClientUrl(String)

Gets a URL that can be used by the browser.

(Inherited from Control)
ResolveUrl(String)

Converts a URL into one that is usable on the requesting client.

(Inherited from Control)
SaveControlState()

Saves the state of the properties in the ListView control that must be persisted, even when the EnableViewState property is set to false.

SaveViewState()

Saves the current view state of the ListView control.

SelectItem(Int32)

Selects the item that is in edit mode in a ListView control.

SetDesignModeState(IDictionary)

Sets design-time data for a control.

(Inherited from Control)
SetEditItem(Int32)

Sets the specified item into edit mode in a ListView control.

SetPageProperties(Int32, Int32, Boolean)

Sets the properties of a page of data in the ListView control.

SetRenderMethodDelegate(RenderMethod)

Assigns an event handler delegate to render the server control and its content into its parent control.

(Inherited from Control)
SetTraceData(Object, Object)

Sets trace data for design-time tracing of rendering data, using the trace data key and the trace data value.

(Inherited from Control)
SetTraceData(Object, Object, Object)

Sets trace data for design-time tracing of rendering data, using the traced object, the trace data key, and the trace data value.

(Inherited from Control)
Sort(String, SortDirection)

Sorts the ListView control, depending on the specified sort expression and direction.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
TrackViewState()

Causes view-state changes to the control to be tracked so they can be stored in the control's StateBag object.

(Inherited from DataBoundControl)
UpdateItem(Int32, Boolean)

Updates the record at the specified index in the data source.

ValidateDataSource(Object)

Verifies that the object a data-bound control binds to is one it can work with.

(Inherited from DataBoundControl)

Events

CallingDataMethods

Occurs when data methods are being called.

(Inherited from DataBoundControl)
CreatingModelDataSource

Occurs when the ModelDataSource object is being created.

(Inherited from DataBoundControl)
DataBinding

Occurs when the server control binds to a data source.

(Inherited from Control)
DataBound

Occurs after the server control binds to a data source.

(Inherited from BaseDataBoundControl)
Disposed

Occurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested.

(Inherited from Control)
Init

Occurs when the server control is initialized, which is the first step in its lifecycle.

(Inherited from Control)
ItemCanceling

Occurs when a cancel operation is requested, but before the ListView control cancels the insert or edit operation.

ItemCommand

Occurs when a button in a ListView control is clicked.

ItemCreated

Occurs when an item is created in a ListView control.

ItemDataBound

Occurs when a data item is bound to data in a ListView control.

ItemDeleted

Occurs when a delete operation is requested, after the ListView control deletes the item.

ItemDeleting

Occurs when a delete operation is requested, but before the ListView control deletes the item.

ItemEditing

Occurs when an edit operation is requested, but before the ListView item is put in edit mode.

ItemInserted

Occurs when an insert operation is requested, after the ListView control has inserted the item in the data source.

ItemInserting

Occurs when an insert operation is requested, but before the ListView control performs the insert.

ItemUpdated

Occurs when an update operation is requested, after the ListView control updates the item.

ItemUpdating

Occurs when an update operation is requested, but before the ListView control updates the item.

LayoutCreated

Occurs when the LayoutTemplate template is created in a ListView control.

Load

Occurs when the server control is loaded into the Page object.

(Inherited from Control)
PagePropertiesChanged

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

PagePropertiesChanging

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

PreRender

Occurs after the Control object is loaded but prior to rendering.

(Inherited from Control)
SelectedIndexChanged

Occurs when an item's Select button is clicked, after the ListView control handles the select operation.

SelectedIndexChanging

Occurs when an item's Select button is clicked, but before the ListView control handles the select operation.

Sorted

Occurs when a sort operation is requested, after the ListView control handles the sort operation.

Sorting

Occurs when a sort operation is requested, but before the ListView control handles the sort operation.

Unload

Occurs when the server control is unloaded from memory.

(Inherited from Control)

Explicit Interface Implementations

IAttributeAccessor.GetAttribute(String)

Gets an attribute of the Web control with the specified name.

(Inherited from WebControl)
IAttributeAccessor.SetAttribute(String, String)

Sets an attribute of the Web control to the specified name and value.

(Inherited from WebControl)
IControlBuilderAccessor.ControlBuilder

For a description of this member, see ControlBuilder.

(Inherited from Control)
IControlDesignerAccessor.GetDesignModeState()

For a description of this member, see GetDesignModeState().

(Inherited from Control)
IControlDesignerAccessor.SetDesignModeState(IDictionary)

For a description of this member, see SetDesignModeState(IDictionary).

(Inherited from Control)
IControlDesignerAccessor.SetOwnerControl(Control)

For a description of this member, see SetOwnerControl(Control).

(Inherited from Control)
IControlDesignerAccessor.UserData

For a description of this member, see UserData.

(Inherited from Control)
IDataBindingsAccessor.DataBindings

For a description of this member, see DataBindings.

(Inherited from Control)
IDataBindingsAccessor.HasDataBindings

For a description of this member, see HasDataBindings.

(Inherited from Control)
IDataBoundControl.DataKeyNames

Gets or sets an array that contains the names of the primary-key fields of the items that are displayed in a data-bound control.

IDataBoundControl.DataMember

Gets or sets the name of the list of data that the data-bound control binds to when the data source contains more than one distinct list of data items.

IDataBoundControl.DataSource

Gets or sets the object from which a data-bound control retrieves its list of data items.

IDataBoundControl.DataSourceID

Gets or sets the ID of the data source control from which a data-bound control retrieves its list of data items.

IDataBoundControl.DataSourceObject

Gets an object that implements the IDataSource interface, which provides access to the object's data content.

IDataBoundListControl.ClientIDRowSuffix

Gets the name of the data field whose value is used to uniquely identify each data row of a ListView control when the ClientIDMode property is set to Predictable.

IDataBoundListControl.DataKeys

Gets a collection of data-key values that represent each row in a data-bound control.

IDataBoundListControl.EnablePersistedSelection

Gets or sets the value that specifies whether a selected row persists when a user pages through data in a data-bound control.

IDataBoundListControl.SelectedDataKey

Gets the data-key object that contains the data-key value for the selected row in a data-bound control.

IDataBoundListControl.SelectedIndex

Gets or sets the index of the selected row in a data-bound control.

IDataKeysControl.ClientIDRowSuffixDataKeys

Gets a collection of the data values that are used to uniquely identify each instance of a data-bound control when ASP.NET generates the ClientID value.

IExpressionsAccessor.Expressions

For a description of this member, see Expressions.

(Inherited from Control)
IExpressionsAccessor.HasExpressions

For a description of this member, see HasExpressions.

(Inherited from Control)
IPageableItemContainer.MaximumRows

For a description of this member, see MaximumRows.

IPageableItemContainer.SetPageProperties(Int32, Int32, Boolean)

For a description of this member, see SetPageProperties(Int32, Int32, Boolean).

IPageableItemContainer.StartRowIndex

For a description of this member, see StartRowIndex.

IPageableItemContainer.TotalRowCountAvailable

For a description of this member, see TotalRowCountAvailable.

IParserAccessor.AddParsedSubObject(Object)

For a description of this member, see AddParsedSubObject(Object).

(Inherited from Control)
IPersistedSelector.DataKey

Gets or sets the data-key value for the selected record in a data-bound control.

Extension Methods

EnablePersistedSelection(BaseDataBoundControl)
Obsolete.

Enables selection to be persisted in data controls that support selection and paging.

FindDataSourceControl(Control)

Returns the data source that is associated with the data control for the specified control.

FindFieldTemplate(Control, String)

Returns the field template for the specified column in the specified control's naming container.

FindMetaTable(Control)

Returns the metatable object for the containing data control.

GetDefaultValues(INamingContainer)

Gets the collection of the default values for the specified data control.

GetMetaTable(INamingContainer)

Gets the table metadata for the specified data control.

SetMetaTable(INamingContainer, MetaTable)

Sets the table metadata for the specified data control.

SetMetaTable(INamingContainer, MetaTable, IDictionary<String,Object>)

Sets the table metadata and default value mapping for the specified data control.

SetMetaTable(INamingContainer, MetaTable, Object)

Sets the table metadata and default value mapping for the specified data control.

TryGetMetaTable(INamingContainer, MetaTable)

Determines whether table metadata is available.

EnableDynamicData(INamingContainer, Type)

Enables Dynamic Data behavior for the specified data control.

EnableDynamicData(INamingContainer, Type, IDictionary<String,Object>)

Enables Dynamic Data behavior for the specified data control.

EnableDynamicData(INamingContainer, Type, Object)

Enables Dynamic Data behavior for the specified data control.

Applies to

See also