按一下以給予評分及指教
.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 樣板所指定的三個項目,以及 EmptyItemTemplate 樣板所指定的兩個項目。

EmptyDataTemplate

定義當資料來源未傳回資料時所要呈現的內容。

SelectedItemTemplate

定義選取的資料項目所要呈現的內容,以區別選取的項目與其他項目。

AlternatingItemTemplate

定義替代項目所要呈現的內容,以輕易區別連續的項目。

EditItemTemplate

定義當編輯項目時所要呈現的內容。對於編輯的資料項目,將會呈現 EditItemTemplate 樣板來取代 ItemTemplate 樣板。

InsertItemTemplate

定義在插入項目時所要呈現的內容。在 ListView 控制項所顯示之項目的開頭或結尾,將會呈現 InsertItemTemplate 樣板來取代 ItemTemplate 樣板。您可以使用 ListView 控制項的 InsertItemPosition 屬性,指定 InsertItemTemplate 樣板呈現的位置。

若要在 ItemTemplate 這類樣板中顯示欄位的值,可以使用資料繫結運算式。如需資料繫結 (Data Binding) 運算式的詳細資訊,請參閱資料繫結運算式概觀

若要將 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(