System.Web.UI.WebControls 命 ...


.NET Framework 类库
ListView 类

更新:2007 年 11 月

使用用户定义的模板显示数据源的值。ListView 控件使用户能够选择、排序、删除、编辑和插入记录。

命名空间:  System.Web.UI.WebControls
程序集:  System.Web.Extensions(在 System.Web.Extensions.dll 中)

语法

Visual Basic(声明)
<ToolboxBitmapAttribute(GetType(ListView), "ListView.ico")> _
<ControlValuePropertyAttribute("SelectedValue")> _
<AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
<AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
Public Class ListView _
    Inherits DataBoundControl _
    Implements INamingContainer, IPageableItemContainer
Visual Basic (用法)
Dim instance As ListView
C#
[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
Visual C++
[ToolboxBitmapAttribute(typeof(ListView), L"ListView.ico")]
[ControlValuePropertyAttribute(L"SelectedValue")]
[AspNetHostingPermissionAttribute(SecurityAction::InheritanceDemand, Level = AspNetHostingPermissionLevel::Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction::LinkDemand, Level = AspNetHostingPermissionLevel::Minimal)]
public ref class ListView : public DataBoundControl, 
    INamingContainer, IPageableItemContainer
J#
/** @attribute ToolboxBitmapAttribute(ListView, "ListView.ico") */
/** @attribute ControlValuePropertyAttribute("SelectedValue") */
/** @attribute AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal) */
/** @attribute AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal) */
public class ListView extends DataBoundControl implements INamingContainer, 
    IPageableItemContainer
JScript
public class ListView extends DataBoundControl implements INamingContainer, IPageableItemContainer
ASP.NET
<asp:ListView />
备注

ListView 控件用于显示数据源的值。它类似于 GridView 控件,区别在于它使用用户定义的模板而不是行字段来显示数据。创建您自己的模板使您可以更灵活地控制数据的显示方式。

ListView 控件支持下列功能:

  • 支持绑定到数据源控件,例如 SqlDataSourceLinqDataSourceObjectDataSource

  • 可通过用户定义的模板和样式自定义外观。

  • 内置排序功能。

  • 内置更新和删除功能。

  • 内置插入功能。

  • 支持通过使用 DataPager 控件进行分页的功能。

  • 内置项选择功能。

  • 以编程方式访问 ListView 对象模型以动态设置属性、处理事件等。

  • 多个键字段。

若要了解 ASP.NET 提供的其他数据绑定控件,请参见 ASP.NET 数据绑定 Web 服务器控件概述

模板

为了使 ListView 控件显示内容,必须为控件的不同部分创建模板。LayoutTemplateItemTemplate 是必需的。其他所有模板都是可选的。

但是,您必须为控件的配置模式创建模板。例如,必须为支持插入记录的 ListView 控件定义 InsertItemTemplate 模板。下表列出了可以为 ListView 控件创建的模板。

模板类型

说明

LayoutTemplate

定义容器对象(例如 tabledivspan 元素)的根模板,该容器对象将包含 ItemTemplateGroupTemplate 模板中定义的内容。它还可能包含一个 DataPager 对象。

ItemTemplate

定义为各项显示的数据绑定内容。

ItemSeparatorTemplate

定义在各项之间呈现的内容。

GroupTemplate

定义容器对象,例如表行 (tr)、divspan 元素,其中将包含 ItemTemplateEmptyItemTemplate 模板中定义的内容。组中显示的项数由 GroupItemCount 属性指定。

GroupSeparatorTemplate

定义在项组之间呈现的内容。

EmptyItemTemplate

定义在使用 GroupTemplate 模板时为空项呈现的内容。例如,如果 GroupItemCount 属性设置为 5,从数据源返回的总项数为 8,则 ListView 控件显示的最后一组数据将包含 ItemTemplate 模板指定的 3 个项和 EmptyItemTemplate 模板指定的 2 个项。

EmptyDataTemplate

定义在数据源未返回数据时呈现的内容。

SelectedItemTemplate

定义为所选数据项呈现的内容,用以区分所选项和其他项。

AlternatingItemTemplate

定义为交替项呈现的内容,以便更容易区分连续项。

EditItemTemplate

定义在编辑项时呈现的内容。对于正在编辑的数据项,将呈现 EditItemTemplate 模板以取代 ItemTemplate 模板。

InsertItemTemplate

定义要呈现以便插入项的内容。将在 ListView 控件显示的项的开始或末尾处呈现 InsertItemTemplate 模板,以取代 ItemTemplate 模板。可以使用 ListView 控件的 InsertItemPosition 属性指定在何处呈现 InsertItemTemplate 模板。

若要显示 ItemTemplate 之类模板中的字段值,可以使用数据绑定表达式。有关数据绑定表达式的更多信息,请参见数据绑定表达式概述

若要将 EditItemTemplateInsertItemTemplate 模板中的输入控件绑定到数据源的字段,可以使用双向绑定表达式。这使得 ListView 控件可以自动提取输入控件的值以进行更新或插入操作。使用双向绑定表达式还可以使 EditItemTemplate 中的输入控件自动显示原始字段值。有关双向绑定表达式的更多信息,请参见绑定到数据库

绑定到数据源

可以将 ListView 控件绑定到数据源控件(例如 SqlDataSourceLinqDataSourceObjectDataSource 等),也可以将其绑定到实现 System.Collections..::.IEnumerable 接口的任何数据源(例如 System.Data..::.DataViewSystem.Collections..::.ArrayListSystem.Collections..::.Hashtable)。使用下列方法之一可将 ListView 控件绑定到适当的数据源类型:

  • 若要绑定到某个数据源控件,请将 ListView 控件的 DataSourceID 属性设置为该数据源控件的 ID 值。ListView 控件自动绑定到指定的数据源控件,并且可以利用数据源控件的功能执行排序、插入、更新、删除和分页功能。这是绑定到数据的首选方法。

  • 若要绑定到某个实现 System.Collections..::.IEnumerable 接口的数据源,请以编程方式将 ListView 控件的 DataSource 属性设置为该数据源,然后调用 DataBind 方法。使用此技术时,ListView 控件不提供内置的排序、更新、删除和分页功能。必须使用适当的事件提供此功能。

有关数据绑定的更多信息,请参见通过 ASP.NET 访问数据

说明:

ListView 控件可用来显示用户输入,而用户输入中可能包含恶意的客户端脚本。在应用程序中显示从客户端发送来的任何信息之前,请检查它们是否包含可执行脚本、SQL 语句或其他代码。在此控件中显示值之前,强烈建议您尽可能对它们进行 HTML 编码。ASP.NET 提供输入请求验证功能以帮助阻止用户输入中的脚本和 HTML。您还可以使用验证服务器控件来检查用户输入。有关更多信息,请参见验证控件介绍

数据操作

ListView 控件绑定到某个数据源控件时,ListView 控件可利用该数据源控件的功能并提供自动排序、插入、更新和删除功能。

说明:

ListView 控件可以为其他类型的数据源提供对排序、插入、更新和删除的支持。但是,若要实现这些操作,必须在适当的事件处理程序中创建代码。

因为 ListView 控件使用模板,所以该控件不提供自动生成按钮以执行更新、删除、插入、排序或选择操作的方法。必须手动将这些按钮包含在适当的模板中。ListView 控件可识别其 CommandName 属性设置为特定值的某些按钮。下表列出了 ListView 控件可以识别的按钮及其功能。

按钮

CommandName 值

说明

取消

“Cancel”

取消编辑或插入操作。引发 ItemCanceling 事件。

删除

“Delete”

从数据源中删除当前记录。引发 ItemDeletedItemDeleting 事件。

选择

“Select”

SelectedIndex 属性设置为项的 DisplayIndex 属性值。呈现项的 SelectedItemTemplate 模板。引发 SelectedIndexChangingSelectedIndexChanged 事件。

编辑

“Edit”

使项处于编辑模式。呈现项的 EditItemTemplate 模板。引发 ItemEditing 事件。

插入

“Insert”

InsertItemTemplate 模板中的绑定值插入到数据源中。引发 ItemInsertingItemInserted 事件。

更新

“Update”

使用 EditItemTemplate 模板中的绑定值更新数据源中的当前记录。引发 ItemUpdatingItemUpdated 事件。

排序

“Sort”

对按钮的 CommandArgument 属性中列出的列进行排序。引发 SortingSorted 事件。

与“删除”按钮(该按钮立刻删除当前数据项)不同,单击“编辑”按钮后,ListView 控件以编辑模式显示当前项。在编辑模式下,将为当前数据项显示 EditItemTemplate 属性中包含的内容。通常,在编辑项模板中,“编辑”按钮被“更新”按钮和“取消”按钮取代。适合于字段的数据类型的输入控件(如 TextBoxCheckBox 控件)通常还显示字段的值以便用户进行修改。单击“更新”按钮可更新数据源中的记录,而单击“取消”按钮可取消编辑操作。

InsertItemPosition 属性设置为 FirstItemLastItem 时,将启用插入功能。此属性定义在何处为插入项呈现 InsertItemTemplate 模板。插入项模板通常包含一个“插入”按钮和一个“取消”按钮,并显示空输入控件以供用户输入新记录的值。单击“插入”按钮可在数据源中插入记录,单击“取消”按钮可清除所有字段。

排序

ListView 控件使用户可以通过单击“排序”按钮对项进行排序。排序功能在包含要排序的列的按钮的 CommandArgument 属性中定义。

分页

ListView 控件可将数据源中的记录分成多页,而不是同时显示所有记录。若要启用分页功能,请将 DataPager 控件与 ListView 控件关联。然后,在 LayoutTemplate 模板中插入一个 DataPager 控件。或者,如果 DataPager 控件位于 ListView 控件外部,请将 PagedControlID 属性设置为 ListView 控件的 ID

事件

下表列出了 ListView 控件支持的事件。

事件

说明

ItemCanceling

在单击“取消”按钮(其 CommandName 属性设置为“Cancel”的按钮)之后、ListView 控件取消插入或编辑操作之前发生。此事件通常用于停止取消操作。

ItemCommand

当单击 ListView 控件中的按钮时发生。此事件通常用于在该控件中的按钮被单击时执行自定义任务。

ItemCreated

ListView 控件中创建新项时发生。此事件通常用于在创建项时修改该项的内容。

ItemDataBound

在将数据项绑定到 ListView 控件中的数据时发生。此事件通常用于在将项绑定到数据时修改该项的内容。

ItemDeleted

在单击“删除”按钮(其 CommandName 属性设置为“Delete”的按钮)或调用 DeleteItem 方法且 ListView 控件从数据源删除记录之后发生。此事件通常用于检查删除操作的结果。

ItemDeleting

在单击“删除”按钮(其 CommandName 属性设置为“Delete”的按钮)或调用 DeleteItem 方法之后、ListView 控件从数据源删除记录之前发生。此事件通常用于确认或取消删除操作。

ItemEditing

在单击“编辑”按钮(其 CommandName 属性设置为“Edit”的按钮)之后、ListView 控件进入编辑模式之前发生。此事件通常用于取消编辑操作。

ItemInserted

在单击“插入”按钮(其 CommandName 属性设置为“Insert”的按钮)或调用 InsertNewItem 方法且 ListView 控件在数据源中插入新记录之后发生。此事件通常用于检查插入操作的结果。

ItemInserting

在单击“插入”按钮(其 CommandName 属性设置为“Insert”的按钮)或调用 InsertNewItem 方法之后、ListView 控件插入记录之前发生。此事件通常用于取消插入操作,或者用于更改或验证新项的值。

ItemUpdated

在单击“更新”按钮(其 CommandName 属性设置为“Update”的按钮)或调用 UpdateItem 方法且 ListView 控件更新记录之后发生。此事件通常用于检查更新操作的结果。

ItemUpdating

在单击“更新”按钮(其 CommandName 属性设置为“Update”的按钮)或调用 UpdateItem 方法之后、ListView 控件更新记录之前发生。此事件通常用于取消更新操作,或者用于更改或验证所编辑的项的值。

LayoutCreated

ListView 控件中创建 LayoutTemplate 模板后发生。此事件通常用于在创建模板后执行任务。

PagePropertiesChanged

在页属性更改且 ListView 控件设置新值之后发生。

PagePropertiesChanging

在数据页属性更改之后、ListView 控件设置新值之前发生。

SelectedIndexChanged

在单击“选择”按钮(其 CommandName 属性设置为“Select”的按钮)且 ListView 控件处理选择操作之后发生。此事件通常用于在控件中选择某项后执行自定义任务。

SelectedIndexChanging

在单击“选择”按钮(其 CommandName 属性设置为“Select”的按钮)之后、ListView 控件处理选择操作之前发生。此事件通常用于取消选择操作。

Sorted

在单击“排序”按钮(其 CommandName 属性设置为“Sort”的按钮)或调用 Sort 方法且 ListView 控件处理排序操作之后发生。此事件通常用于在用户单击“排序”按钮并且已经对数据进行排序后执行自定义任务。

Sorting

在单击“排序”按钮(其 CommandName 属性设置为“Sort”的按钮)或调用 Sort 方法之后、ListView 控件处理排序操作之前发生。此事件通常用于取消排序操作或执行自定义的排序例程。

TopicLocation
演练:使用 ListView Web 服务器控件修改数据使用 Visual Web Developer 生成应用程序
演练:使用 ListView Web 服务器控件对数据进行显示、分页和排序使用 Visual Web Developer 生成应用程序
演练:创建支持 AJAX 的数据应用程序使用 Visual Web Developer 生成应用程序
示例

下面的示例演示如何使用 ListView 控件通过 HTML 表显示数据库中的记录。这些值是使用 LinqDataSource 控件检索的。

Visual Basic
<%@ Page language="VB" %>

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

<html  >
  <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>
C#
<%@ Page language="C#" %>

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

<html  >
  <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>

下面的示例演示如何使用 ListView 控件通过 div 元素显示流布局中的值。这些值是使用 SqlDataSource 控件检索的。

Visual Basic
<%@ Page language="VB" %>

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

<html  >
  <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>
C#
<%@ Page language="C#" %>

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

<html  >
  <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>

下面的示例演示如何使用 ListView 控件插入、删除和更新记录。

安全说明:

此示例有一个接受用户输入的文本框,这是一个潜在的安全威胁。默认情况下,ASP.NET 网页验证用户输入是否不包括脚本或 HTML 元素。有关更多信息,请参见脚本侵入概述

Visual Basic
<%@ Page language="VB" %>

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

<html  >
  <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>
C#
<%@ Page language="C#" %>

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

<html  >
  <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>
权限

继承层次结构

System..::.Object
  System.Web.UI..::.Control
    System.Web.UI.WebControls..::.WebControl
      System.Web.UI.WebControls..::.BaseDataBoundControl
        System.Web.UI.WebControls..::.DataBoundControl
          System.Web.UI.WebControls..::.ListView
线程安全

此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。
平台

Windows Vista, Windows XP SP2, Windows Server 2003

.NET Framework 和 .NET Compact Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求

版本信息

.NET Framework

受以下版本支持:3.5
另请参见

参考

其他资源

标记 :


Page view tracker