Share via


DataGrid Web 伺服器控制項宣告式語法

更新:2007 年 11 月

DataGrid 控制項會呈現表格式的資料繫結格。這個控制項可以讓您定義各種類型的資料行來控制這些方格 (繫結資料行、樣板資料行) 之儲存格內容的配置,並且加入特定的功能 (例如編輯按鈕資料行、超連結資料行等)。這個控制項也支援資料分頁的各種選項。

 <asp:DataGrid     AccessKey="string"     AllowCustomPaging="True|False"     AllowPaging="True|False"     AllowSorting="True|False"     AutoGenerateColumns="True|False"     BackColor="color name|#dddddd"     BackImageUrl="uri"     BorderColor="color name|#dddddd"     BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|         Inset|Outset"     BorderWidth="size"     Caption="string"     CaptionAlign="NotSet|Top|Bottom|Left|Right"     CellPadding="integer"     CellSpacing="integer"     CssClass="string"     DataKeyField="string"     DataMember="string"     DataSource="string"     DataSourceID="string"     EditItemIndex="integer"     Enabled="True|False"     EnableTheming="True|False"     EnableViewState="True|False"     Font-Bold="True|False"     Font-Italic="True|False"     Font-Names="string"     Font-Overline="True|False"     Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|Medium|         Large|X-Large|XX-Large"     Font-Strikeout="True|False"     Font-Underline="True|False"     ForeColor="color name|#dddddd"     GridLines="None|Horizontal|Vertical|Both"     Height="size"     HorizontalAlign="NotSet|Left|Center|Right|Justify"     ID="string"     OnCancelCommand="CancelCommand event handler"     OnDataBinding="DataBinding event handler"     OnDeleteCommand="DeleteCommand event handler"     OnDisposed="Disposed event handler"     OnEditCommand="EditCommand event handler"     OnInit="Init event handler"     OnItemCommand="ItemCommand event handler"     OnItemCreated="ItemCreated event handler"     OnItemDataBound="ItemDataBound event handler"     OnLoad="Load event handler"     OnPageIndexChanged="PageIndexChanged event handler"     OnPreRender="PreRender event handler"     OnSelectedIndexChanged="SelectedIndexChanged event handler"     OnSortCommand="SortCommand event handler"     OnUnload="Unload event handler"     OnUpdateCommand="UpdateCommand event handler"     PageSize="integer"     runat="server"     SelectedIndex="integer"     ShowFooter="True|False"     ShowHeader="True|False"     SkinID="string"     Style="string"     TabIndex="integer"     ToolTip="string"     UseAccessibleHeader="True|False"     Visible="True|False"     Width="size" >         <AlternatingItemStyle />         <Columns>                 <asp:BoundColumn                     DataField="string"                     DataFormatString="string"                     FooterText="string"                     HeaderImageUrl="uri"                     HeaderText="string"                     ReadOnly="True|False"                     SortExpression="string"                     Visible="True|False" >                         <FooterStyle />                         <HeaderStyle />                         <ItemStyle />                 </asp:BoundColumn>                 <asp:ButtonColumn                     ButtonType="LinkButton|PushButton"                     CausesValidation="True|False"                     CommandName="string"                     DataTextField="string"                     DataTextFormatString="string"                     FooterText="string"                     HeaderImageUrl="uri"                     HeaderText="string"                     SortExpression="string"                     Text="string"                     ValidationGroup="string"                     Visible="True|False" >                         <FooterStyle />                         <HeaderStyle />                         <ItemStyle />                 </asp:ButtonColumn>                 <asp:EditCommandColumn                     ButtonType="LinkButton|PushButton"                     CancelText="string"                     CausesValidation="True|False"                     EditText="string"                     FooterText="string"                     HeaderImageUrl="uri"                     HeaderText="string"                     SortExpression="string"                     UpdateText="string"                     ValidationGroup="string"                     Visible="True|False" >                         <FooterStyle />                         <HeaderStyle />                         <ItemStyle />                 </asp:EditCommandColumn>                 <asp:HyperLinkColumn                     DatahrefField="string"                     DatahrefFormatString="string"                     DataTextField="string"                     DataTextFormatString="string"                     FooterText="string"                     HeaderImageUrl="uri"                     HeaderText="string"                     href="uri"                     SortExpression="string"                     Target="string|_blank|_parent|_search|_self|_top"                     Text="string"                     Visible="True|False" >                         <FooterStyle />                         <HeaderStyle />                         <ItemStyle />                 </asp:HyperLinkColumn>                 <asp:TemplateColumn                     FooterText="string"                     HeaderImageUrl="uri"                     HeaderText="string"                     SortExpression="string"                     Visible="True|False" >                             <FooterStyle />                             <HeaderStyle />                             <ItemStyle />                         <EditItemTemplate>                             <!-- child controls -->                         </EditItemTemplate>                         <FooterTemplate>                             <!-- child controls -->                         </FooterTemplate>                         <HeaderTemplate>                             <!-- child controls -->                         </HeaderTemplate>                         <ItemTemplate>                             <!-- child controls -->                         </ItemTemplate>                 </asp:TemplateColumn>         </Columns>         <EditItemStyle />         <FooterStyle />         <HeaderStyle />         <ItemStyle />         <PagerStyle             BackColor="color name|#dddddd"             BorderColor="color name|#dddddd"             BorderStyle="NotSet|None|Dotted|Dashed|Solid|Double|                 Groove|Ridge|Inset|Outset"             BorderWidth="size"             CssClass="string"             Font-Bold="True|False"             Font-Italic="True|False"             Font-Names="string"             Font-Overline="True|False"             Font-Size="string|Smaller|Larger|XX-Small|X-Small|Small|                 Medium|Large|X-Large|XX-Large"             Font-Strikeout="True|False"             Font-Underline="True|False"             ForeColor="color name|#dddddd"             Height="size"             HorizontalAlign="NotSet|Left|Center|Right|Justify"             Mode="NextPrev|NumericPages"             NextPageText="string"             OnDisposed="Disposed event handler"             PageButtonCount="integer"             Position="Bottom|Top|TopAndBottom"             PrevPageText="string"             VerticalAlign="NotSet|Top|Middle|Bottom"             Visible="True|False"             Width="size"             Wrap="True|False"         />         <SelectedItemStyle /> </asp:DataGrid>

備註

在使用 DataGrid 控制項之前,請先考慮改用 GridView 控制項。GridView 控制項是 .NET Framework 2.0 版中的新功能,並且是 DataGrid 控制項的繼承者。

DataGrid 控制項會將資料來源的欄位顯示為資料表中的資料行。DataGrid 控制項中的每個資料列都代表資料來源中的一筆資料錄。DataGrid 控制項支援選取、編輯、刪除、分頁和排序。

根據預設,AutoGenerateColumns 屬性設定為 true,它會為資料來源中的每個欄位都建立一個 BoundColumn 物件。然後每個欄位會依各個欄位在資料來源中出現的順序,呈現為 DataGrid 控制項中的資料行。

您也可以將 AutoGenerateColumns 屬性設定為 false,並且在開頭和結尾的 <Columns> 標記之間列出您想要包含的資料行,即可以手動方式控制哪些資料行要出現在 DataGrid 控制項中。所指定的資料行就會依列出的順序加入至 Columns 集合中。這樣您就可以以程式設計的方式控制 DataGrid 控制項中的資料行。

注意事項:

資料行在 DataGrid 控制項中的顯示順序,是由資料行在 Columns 集合中出現的順序所控制。雖然您可以操作 Columns 集合,以程式設計的方式變更資料行的順序,但依照需要的顯示順序列出資料行會比較容易。

注意事項:

明確宣告的資料行可以配合自動產生的資料行使用。當兩者都使用時,明確宣告的資料行將首先呈現,接著是自動產生的資料行。自動產生的資料行不會加入至 Columns 集合中。

不同的資料行型別決定控制項中的資料行行為。DataGrid 控制項允許您使用下列資料行型別。

資料行型別

描述

EditCommandColumn

將最常用的編輯命令 (Edit、Update、Cancel、) 封裝到預先定義的資料行型別中。

HyperLinkColumn

用一組繫結至資料欄位值的超連結來建立資料行。例如,顯示訂購清單的方格可以包括超連結資料行,其中的 OrderID 欄位會呈現為顯示訂單詳細資料之網頁的超連結。

BoundColumn

建立繫結至資料來源中欄位的資料行,並且使用樣式呈現資料表儲存格。這是 DataGrid 控制項的預設資料行型別。

ButtonColumn

為資料行中每一項目建立包含使用者定義命令按鈕 (例如 Add 或 Remove) 的資料行。

TemplateColumn

建立可以讓您使用自訂 HTML 項目和控制項的樣板定義,來控制項之配置的資料行。

下表提供可為 DataGrid 控制項宣告之資料行的相關資訊。

DataGridColumn 基礎屬性

在所有的 DataGrid 資料行型別上都可使用下列屬性。

屬性

描述

FooterText

要顯示在資料行底緣的文字。

HeaderImageUrl

替代 HeaderText 文字呈現在資料行行首之影像的 URL。

HeaderText

要顯示在資料行頂緣的文字。

Owner

繫結資料行所屬之 DataGrid 控制項的參考 (唯讀)。

這個屬性只能在撰寫程式時使用。

SortExpression

當使用者指定依據這個資料行的內容排序時,用來排序資料來源的欄位名稱。

Visible

如果顯示資料行則為 true,否則為 false。

BoundColumn 屬性

屬性

描述

DataField

DataSource 中的欄位或物件屬性,為該資料行的資料來源。

DataFormatString

指定欄位在儲存格中如何顯示的格式運算式字串。這很類似 Format 方法所使用的格式運算式。

ReadOnly

如果將資料列置入編輯模式卻無法編輯資料行,則為 true,否則為 false。

ButtonColumn 屬性

屬性

描述

ButtonType

要呈現之按鈕的類型。預設值為 LinkButton

在撰寫程式時,這個屬性是以 ButtonColumnType 進行設定。

CommandName

表示按一下資料行中某一按鈕時所傳送之命令的字串。這個字串可以透過 e 事件引數物件的 CommandSource 屬性,在事件處理方法中取得。

DataGrid 控制項可以辨識某些標準命令的名稱。這些命令名稱包括 Select、Sort、Update、Cancel、Edit、Delete 和 Page。

DataTextField

DataSource 中的欄位名稱,繫結至 ButtonColumn 中按鈕的 Text 屬性。

DataTextFormatString

指定欄位在儲存格中如何顯示的格式運算式字串。

Text

要顯示在這個資料行中按鈕表面上的標題。如果有設定 DataTextField,它就會覆寫這個值。

TemplateColumn 屬性

屬性

描述

EditItemTemplate

定義編輯模式中之資料行的 HTML 項目和控制項。

FooterTemplate

定義資料行行尾的 HTML 項目和控制項。

HeaderTemplate

定義資料行行首的 HTML 項目和控制項。

ItemTemplate

定義在顯示狀態之資料行的 HTML 項目和控制項。

HyperLinkColumn 屬性

屬性

描述

DatahrefField

DataSource 中的欄位或物件屬性,提供所要前往之網頁的 URL。

DatahrefFormatString

要配合 Text 屬性使用的格式運算式。

DataTextField

DataSource 中物件的欄位或屬性,為資料行 Text 屬性的資料來源。

DataTextFormatString

指定要如何在控制項中顯示 Text 屬性的格式字串。

href

要前往之網頁的 URL。如果有設定 DatahrefField,它就會覆寫這個屬性。

Target

顯示網頁的目標視窗。這可以是視窗名稱或框架 (Frame) 參考 (例如 _TOP)。

Text

超連結的文字。

EditCommandColumn 屬性

屬性

描述

ButtonType

要呈現之按鈕的類型。預設值為 LinkButton。

在撰寫程式時,這個屬性是以 ButtonColumnType 進行設定。

EditText

在 [Edit] 按鈕表面顯示的字串。

UpdateText

在 [Update] 按鈕表面顯示的字串。

CancelText

在 [Cancel] 按鈕表面顯示的字串。

您可以設定控制項不同部分的樣式屬性,自訂 DataGrid 控制項的外觀。下表所列即為 DataGrid 控制項不同部分的樣式屬性。

樣式屬性

樣式屬性

描述

樣式類別

AlternatingItemStyle

每隔一個項目 (替代項目) 的樣式。

TableItemStyle

EditItemStyle

編輯中項目的樣式。

TableItemStyle

FooterStyle

位於清單結尾的行尾樣式 (如果有)。

TableItemStyle

HeaderStyle

位於清單開頭的行首樣式 (如果有)。

TableItemStyle

ItemStyle

個別項目的樣式。

Style

PagerStyle

頁面選取範圍控制項的樣式。

DataGridPagerStyle

SelectedItemStyle

目前選取項目的樣式。

TableItemStyle

如需每種樣式類別所支援之屬性的詳細資訊,請參閱樣式物件屬性

DataGrid 控制項含有在網頁區段中顯示其內容的內建功能。網頁上項目的數目是由 PageSize 屬性所決定。如果沒有指定 PageSize 屬性的值,DataGrid 控制項就會在網頁上一次顯示十個項目。

預設情況下,將會啟用分頁。若要啟用分頁,請將 AllowPaging 屬性設定為 true,並提供處理 PageIndexChanged 事件的程式碼。PageIndexChanged 事件的基本邏輯是將 CurrentPageIndex 屬性設定為要顯示之網頁的索引,然後將資料來源重新繫結至控制項。對於要顯示的網頁索引,通常會使用傳遞至事件處理常式之 DataGridPageChangedEventArgs 物件的 NewPageIndex 屬性進行存取。

使用標準分頁時,DataGrid 控制項會假設資料來源包含要顯示的所有項目。DataGrid 控制項會根據 CurrentPageIndex 屬性所指定的頁面索引,和 PageSize 屬性所指定頁面中的項目數目,計算目前頁面中項目的索引。

以程式設計方式將屬性 (Attribute) 加入至 DataGrid 控制項所產生的 <td> 和 <tr> 標記,即可自訂 DataGrid 控制項的外觀。藉由提供 ItemCreatedItemDataBound 事件的自訂事件處理常式,就能將屬性插入至標記中。一般而言,屬性會加入 ItemCreated 事件的事件處理常式中。但是,如果屬性取決於實際資料,則應將屬性加入至 ItemDataBound 事件的處理常式中。

若要將屬性加入至 <td> 標記,請先取得代表您要加入屬性之 DataGrid 控制項中儲存格的 TableCell 物件。傳遞至事件處理常式中之 DataGridItemEventArgs 的 Item 屬性 (DataGridItemEventArgs 索引子 (Indexer)) 的 Control.Controls 集合,可以用來取得需要的 TableCell。然後您就可以使用 TableCell 之 Attributes 集合的 AttributeCollection.Add 方法,將屬性加入至 <td> 標記中。

若要將屬性加入至 <tr> 標記,請先取得代表您要加入屬性之 DataGrid 控制項中資料列的 DataGridItem。傳遞至事件處理常式中之 DataGridItemEventArgs 的 Item 屬性 (DataGridItemEventArgs 索引子),可以用來取得需要的 DataGridItem。然後您就可以使用 DataGridItem 之 Attributes 集合的 AttributeCollection.Add 方法,將屬性加入至 <tr> 標記中。

警告:

尚未顯示於 DataGrid 控制項中的文字,便還未經過 HTML 編碼。這樣便可以在文字中的 HTML 標記內嵌入指令碼。如果控制項的值來自使用者輸入,請務必驗證值來協助防止安全性的弱點。

如需 DataGrid Web 伺服器控制項之屬性和事件的詳細資訊,請參閱 DataGrid 類別文件。

範例

下列範例示範如何使用 DataGrid 控制項顯示資料來源中的項目。

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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" >
   <script language="VB" runat="server">
     Function CreateDataSource() As ICollection
        Dim dt As New DataTable()
        Dim dr As DataRow

        dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
        dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
        dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))

        Dim i As Integer
        For i = 0 To 8
            dr = dt.NewRow()

            dr(0) = i
            dr(1) = "Item " + i.ToString()
            dr(2) = 1.23 *(i + 1)

            dt.Rows.Add(dr)
        Next i

        Dim dv As New DataView(dt)
        Return dv
    End Function 'CreateDataSource


    Sub Page_Load(sender As Object, e As EventArgs)

        If Not IsPostBack Then
            ' Load this data only once.
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End If
    End Sub 'Page_Load

  </script>

<head runat="server">
    <title>DataGrid Example</title>
</head>
<body>

   <form id="form1" runat="server">

      <h3>DataGrid Example</h3>

      <b>Product List</b>

      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AutoGenerateColumns="true"
           runat="server">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle> 

      </asp:DataGrid>

   </form>

</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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" >
   <script language="C#" runat="server">

      ICollection CreateDataSource() 
      {
         DataTable dt = new DataTable();
         DataRow dr;

         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));

         for (int i = 0; i < 9; i++) 
         {
            dr = dt.NewRow();

            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i + 1);

            dt.Rows.Add(dr);
         }

         DataView dv = new DataView(dt);
         return dv;
      }

      void Page_Load(Object sender, EventArgs e) 
      {

         if (!IsPostBack) 
         {
            // Load this data only once.
            ItemsGrid.DataSource= CreateDataSource();
            ItemsGrid.DataBind();
         }
      }

   </script>

<head runat="server">
    <title>DataGrid Example</title>
</head>
<body>

   <form id="form1" runat="server">

      <h3>DataGrid Example</h3>

      <b>Product List</b>

      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           AutoGenerateColumns="true"
           runat="server">

         <HeaderStyle BackColor="#00aaaa">
         </HeaderStyle> 

      </asp:DataGrid>

   </form>

</body>
</html>

下列範例示範如何在 DataGrid 控制項中使用分頁。

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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" >
<script language="VB" runat="server">

        Dim Cart As DataTable
        Dim CartView As DAtaView

        Function CreateDataSource() As ICollection
            Dim dt As New DataTable()
            Dim dr As DataRow

            dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
            dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
            dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))

            Dim i As Integer
            For i = 0 To 99
                dr = dt.NewRow()

                dr(0) = i
                dr(1) = "Item " + i.ToString()
                dr(2) = 1.23 *(i + 1)
                dt.Rows.Add(dr)
            Next i

            Dim dv As New DataView(dt)
            Return dv
        End Function 'CreateDataSource


        Sub Page_Load(sender As Object, e As EventArgs)

            If Not IsPostBack Then
                ' Need to load this data only once.
                ItemsGrid.DataSource = CreateDataSource()
                ItemsGrid.DataBind()
            End If

            If CheckBox1.Checked Then
                ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages
            Else
                ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev
            End If 
        End Sub 'Page_Load


        Sub Grid_Change(sender As Object, e As DataGridPageChangedEventArgs)

            ' Set CurrentPageIndex to the page the user clicked.
            ItemsGrid.CurrentPageIndex = e.NewPageIndex

            ' Rebind the data. 
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End Sub 'Grid_Change  
</script>

<head runat="server">
    <title>DataGrid Paging Example</title>
</head>
<body>

   <form id="form1" runat="server">

   <h3>DataGrid Paging Example</h3>

   <asp:DataGrid id="ItemsGrid" runat="server"
        BorderColor="black"
        BorderWidth="1"
        CellPadding="3"
        AllowPaging="true"
        AutoGenerateColumns="false"        
        OnPageIndexChanged="Grid_Change">

      <HeaderStyle BackColor="#00aaaa">
      </HeaderStyle>

      <PagerStyle Mode="NextPrev">
      </PagerStyle> 

      <Columns>

         <asp:BoundColumn 
              HeaderText="Number" 
              DataField="IntegerValue"/>

        <asp:BoundColumn 
              HeaderText="Item" 
              DataField="StringValue"/>

         <asp:BoundColumn 
              HeaderText="Price" 
              DataField="CurrencyValue" 
              DataFormatString="{0:c}">

            <ItemStyle HorizontalAlign="right">
            </ItemStyle>

         </asp:BoundColumn>

      </Columns>

   </asp:DataGrid>

   <br />

   <asp:CheckBox id="CheckBox1" 
                 Text="Show page navigation"
                 AutoPostBack="true"
                 runat="server"/>

   </form>

</body>
</html>

<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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" >
<script language="C#" runat="server">

   DataTable Cart;
   DataView CartView;

   ICollection CreateDataSource() 
   {
      DataTable dt = new DataTable();
      DataRow dr;

      dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
      dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
      dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));

      for (int i = 0; i < 100; i++) 
      {
         dr = dt.NewRow();

         dr[0] = i;
         dr[1] = "Item " + i.ToString();
         dr[2] = 1.23 * (i+1); 
         dt.Rows.Add(dr);
      }

      DataView dv = new DataView(dt);
      return dv;
   }

   void Page_Load(Object sender, EventArgs e) 
   {

      if (!IsPostBack) 
      {
         // Need to load this data only once.
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();
      }

      if (CheckBox1.Checked)
         ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages;
      else
         ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev;

   }

   void Grid_Change(Object sender, DataGridPageChangedEventArgs e) 
   {

      // Set CurrentPageIndex to the page the user clicked.
      ItemsGrid.CurrentPageIndex = e.NewPageIndex;

      // Rebind the data. 
      ItemsGrid.DataSource = CreateDataSource();
      ItemsGrid.DataBind();

   }


</script>

<head runat="server">
    <title>DataGrid Paging Example</title>
</head>
<body>

   <form id="form1" runat="server">

   <h3>DataGrid Paging Example</h3>

   <asp:DataGrid id="ItemsGrid" runat="server"
        BorderColor="black"
        BorderWidth="1"
        CellPadding="3"
        AllowPaging="true"
        AutoGenerateColumns="false"        
        OnPageIndexChanged="Grid_Change">

      <HeaderStyle BackColor="#00aaaa">
      </HeaderStyle>

      <PagerStyle Mode="NextPrev">
      </PagerStyle> 

      <Columns>

         <asp:BoundColumn 
              HeaderText="Number" 
              DataField="IntegerValue"/>

        <asp:BoundColumn 
              HeaderText="Item" 
              DataField="StringValue"/>

         <asp:BoundColumn 
              HeaderText="Price" 
              DataField="CurrencyValue" 
              DataFormatString="{0:c}">

            <ItemStyle HorizontalAlign="right">
            </ItemStyle>

         </asp:BoundColumn>

      </Columns>

   </asp:DataGrid>

   <br />

   <asp:CheckBox id="CheckBox1" 
                 Text="Show page navigation"
                 AutoPostBack="true"
                 runat="server"/>

   </form>

</body>
</html>

<%@ Page Language="JScript" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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" >
<script language="JScript" runat="server">

   var Cart : DataTable;
   var CartView : DataView;

   function CreateDataSource () : ICollection
   {
      var dt : DataTable = new DataTable();
      var dr : DataRow;

      dt.Columns.Add(new DataColumn("IntegerValue", Int32));
      dt.Columns.Add(new DataColumn("StringValue", System.String));
      dt.Columns.Add(new DataColumn("CurrencyValue", double));

      for (var i : int = 0; i < 100; i++) 
      {
         dr = dt.NewRow();

         dr[0] = i;
         dr[1] = "Item " + i.ToString();
         dr[2] = 1.23 * (i+1); 
         dt.Rows.Add(dr);
      }

      var dv : DataView = new DataView(dt);
      return dv;
   }

   function Page_Load(sender, e : EventArgs) 
   {

      if (!IsPostBack) 
      {
         // Need to load this data only once.
         ItemsGrid.DataSource = CreateDataSource();
         ItemsGrid.DataBind();
      }

      if (CheckBox1.Checked)
         ItemsGrid.PagerStyle.Mode = PagerMode.NumericPages;
      else
         ItemsGrid.PagerStyle.Mode = PagerMode.NextPrev;

   }

   function Grid_Change(sender, e : DataGridPageChangedEventArgs) 
   {

      // Set CurrentPageIndex to the page the user clicked.
      ItemsGrid.CurrentPageIndex = e.NewPageIndex;

      // Rebind the data. 
      ItemsGrid.DataSource = CreateDataSource();
      ItemsGrid.DataBind();

   }


</script>

<head runat="server">
    <title>DataGrid Paging Example</title>
</head>
<body>

   <form id="form1" runat="server">

   <h3>DataGrid Paging Example</h3>

   <asp:DataGrid id="ItemsGrid" runat="server"
        BorderColor="black"
        BorderWidth="1"
        CellPadding="3"
        AllowPaging="true"
        AutoGenerateColumns="false"        
        OnPageIndexChanged="Grid_Change">

      <HeaderStyle BackColor="#00aaaa">
      </HeaderStyle>

      <PagerStyle Mode="NextPrev">
      </PagerStyle> 

      <Columns>

         <asp:BoundColumn 
              HeaderText="Number" 
              DataField="IntegerValue"/>

        <asp:BoundColumn 
              HeaderText="Item" 
              DataField="StringValue"/>

         <asp:BoundColumn 
              HeaderText="Price" 
              DataField="CurrencyValue" 
              DataFormatString="{0:c}">

            <ItemStyle HorizontalAlign="right">
            </ItemStyle>

         </asp:BoundColumn>

      </Columns>

   </asp:DataGrid>

   <br />

   <asp:CheckBox id="CheckBox1" 
                 Text="Show page navigation"
                 AutoPostBack="true"
                 runat="server"/>

   </form>

</body>
</html>

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>

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

<script runat="server">
    Function CreateDataSource() As ICollection
        ' Create sample data for the DataGrid control.
        Dim dt As DataTable = New DataTable()
        Dim dr As DataRow

        ' Define the columns of the table.
        dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
        dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
        dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))

        ' Populate the table with sample values.
        Dim i As Integer
        For i = 0 To 100
            dr = dt.NewRow()
            dr(0) = i
            dr(1) = "Item " & i.ToString()
            dr(2) = 1.23 * (i + 1)
            dt.Rows.Add(dr)
        Next i

        Dim dv As DataView = New DataView(dt)
        Return dv
    End Function

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ' Load sample data only once, when the page is first loaded.
        If Not IsPostBack Then
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End If
    End Sub

    Sub Check_Change(ByVal sender As Object, ByVal e As EventArgs)
        ' Allow or prevent paging depending on the user's selection.
        ItemsGrid.AllowPaging = AllowPagingCheckBox.Checked()

        ' Rebind the data to refresh the DataGrid control. 
        ItemsGrid.DataSource = CreateDataSource()
        ItemsGrid.DataBind()
    End Sub

    Sub Grid_Change(ByVal sender As Object, ByVal e As DataGridPageChangedEventArgs)
        ' For the DataGrid control to navigate to the correct page when
        ' paging is allowed, the CurrentPageIndex property must be updated
        ' programmatically. This process is usually accomplished in the
        ' event-handling method for the PageIndexChanged event.

        ' Set CurrentPageIndex to the page the user clicked.
        ItemsGrid.CurrentPageIndex = e.NewPageIndex

        ' Rebind the data to refresh the DataGrid control. 
        ItemsGrid.DataSource = CreateDataSource()
        ItemsGrid.DataBind()
    End Sub
</script>

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

    <h3>DataGrid AllowPaging Example</h3>

    <p>Select whether to allow paging in the DataGrid control.<br />
       <asp:CheckBox id="AllowPagingCheckBox"
            Text="Allow paging"
            AutoPostBack="True"
            Checked="True"
            OnCheckedChanged="Check_Change"
            runat="server" />
    </p>
    <hr />
    <asp:Label ID="Label1" runat="server" 
        AssociatedControlID="ItemsGrid" 
        Font-Bold="true">Product List</asp:Label>
    <asp:DataGrid id="ItemsGrid" runat="server"
        BorderColor="Gray"
        BorderWidth="1"
        CellPadding="3"
        UseAccessibleHeader="true"
        AutoGenerateColumns="False"
        PageSize="10"
        AllowPaging="True"
        OnPageIndexChanged="Grid_Change">

        <HeaderStyle BackColor="LightBlue" />
        <Columns>
            <asp:BoundColumn DataField="IntegerValue" 
                 SortExpression="IntegerValue"
                 ItemStyle-HorizontalAlign="center"
                 HeaderText="Item" />

            <asp:BoundColumn DataField="StringValue" 
                HeaderText="Description" 
                ItemStyle-HorizontalAlign="left"
                SortExpression="StringValue" />

            <asp:BoundColumn DataField="CurrencyValue" 
                 HeaderText="Price"
                 SortExpression="CurrencyValue"
                 DataFormatString="{0:c}" />

        </Columns>
        <ItemStyle HorizontalAlign="Right" />
    </asp:DataGrid>

    </div>
    </form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>

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

<script runat="server">
    private ICollection CreateDataSource()
    {
        // Create sample data for the DataGrid control.
        DataTable dt = new DataTable();
        DataRow dr;

        // Define the columns of the table.
        dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
        dt.Columns.Add(new DataColumn("StringValue", typeof(String)));
        dt.Columns.Add(new DataColumn("CurrencyValue", typeof(Double)));

        // Populate the table with sample values.
        for (int i = 0; i <= 100; i++) 
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = "Item " + i.ToString();
            dr[2] = 1.23 * (i + 1);

            dt.Rows.Add(dr);
        }
        DataView dv = new DataView(dt);
        return dv;
    }

    private void Page_Load(Object sender, EventArgs e)
    { 
        // Load sample data only once, when the page is first loaded.
        if (!IsPostBack)
        { 
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
        }
    }

    private void Check_Change(Object sender, EventArgs e)
    {
        // Allow or prevent paging depending 
        // on the user's selection.
        ItemsGrid.AllowPaging = AllowPagingCheckBox.Checked;

        // Rebind the data to refresh the DataGrid control. 
        ItemsGrid.DataSource = CreateDataSource();
        ItemsGrid.DataBind();
    }

    private void Grid_Change(Object sender, DataGridPageChangedEventArgs e) 
    {
        // For the DataGrid control to navigate to the correct page when
        // paging is allowed, the CurrentPageIndex property must be updated
        // programmatically. This process is usually accomplished in the
        // event-handling method for the PageIndexChanged event.

        // Set CurrentPageIndex to the page the user clicked.
        ItemsGrid.CurrentPageIndex = e.NewPageIndex;

        // Rebind the data to refresh the DataGrid control. 
        ItemsGrid.DataSource = CreateDataSource();
        ItemsGrid.DataBind();
    }
</script>

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

    <h3>DataGrid AllowPaging Example</h3>

    <p>Select whether to allow paging in the DataGrid control.<br />
       <asp:CheckBox id="AllowPagingCheckBox"
            Text="Allow paging"
            AutoPostBack="True"
            Checked="True"
            OnCheckedChanged="Check_Change"
            runat="server" />
    </p>
    <hr />
    <asp:Label runat="server" 
        AssociatedControlID="ItemsGrid" 
        Font-Bold="true">Product List</asp:Label>
    <asp:DataGrid id="ItemsGrid" runat="server"
        BorderColor="Gray"
        BorderWidth="1"
        CellPadding="3"
        AutoGenerateColumns="False"
        UseAccessibleHeader="true"
        PageSize="10"
        AllowPaging="True"
        OnPageIndexChanged="Grid_Change">

        <HeaderStyle BackColor="LightBlue" />
        <Columns>
            <asp:BoundColumn DataField="IntegerValue" 
                 SortExpression="IntegerValue"
                 ItemStyle-HorizontalAlign="center"
                 HeaderText="Item" />

            <asp:BoundColumn DataField="StringValue" 
                HeaderText="Description" 
                ItemStyle-HorizontalAlign="left"
                SortExpression="StringValue" />

            <asp:BoundColumn DataField="CurrencyValue" 
                 HeaderText="Price"
                 SortExpression="CurrencyValue"
                 DataFormatString="{0:c}" />

        </Columns>
        <ItemStyle HorizontalAlign="Right" />
    </asp:DataGrid>

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

基本上,每當 DataGrid 控制項顯示資訊網頁時,便會載入含有清單中所有項目的資料來源。可是當資料來源非常大的時候,這樣將會消耗許多資源。自訂分頁可以讓您只載入顯示網頁所需的資料區段。

若要啟用分頁,請將 AllowPaging 屬性 和 AllowCustomPaging 屬性設定為 true,並提供處理 PageIndexChanged 事件的程式碼。PageIndexChanged 事件的基本邏輯是將 CurrentPageIndex 屬性設定為要顯示之網頁的索引,然後將資料來源重新繫結至控制項。對於要顯示的網頁索引,通常會使用傳遞至事件處理常式之 DataGridPageChangedEventArgs 物件的 NewPageIndex 屬性進行存取。接下來,建立含有要顯示在單一網頁上之資料的資料來源。建立資料來源之後,使用 DataBind 方法將資料來源繫結至 DataGrid 控制項。因為只有一個資料區段會被載入,所以請將 VirtualItemCount 屬性設定為您要顯示在 DataGrid 控制項中之項目的總數。這樣可以讓控制項來決定分頁控制項所需的網頁總數。

使用自訂分頁時,DataGrid 控制項會假設資料來源只含有要顯示在目前網頁上的項目。資料來源的所有項目中,最多可以顯示由 PageSize 屬性所指定的項目數目。

下列程式碼範例會示範如何使用 AllowCustomPaging 屬性啟用自訂分頁。

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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" >

   <script runat="server">

      ' Normally, an entire data source is loaded in the DataGrid control, 
      ' which can take up a lot of resources. This example uses custom 
      ' paging, which loads only the segment of data needed to fill a
      ' single page. In order to query for the appropriate segment of
      ' data, the index of the first item displayed on a page must be
      ' tracked as the user navigates between pages.
      Dim startIndex As Integer = 0

      Function CreateDataSource() As ICollection 

         ' Create sample data for the DataGrid control.
         Dim dt As DataTable = New DataTable()
         Dim dr As DataRow

         ' Define the columns of the table.
         dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
         dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
         dt.Columns.Add(New DataColumn("DateTimeValue", GetType(String)))
         dt.Columns.Add(New DataColumn("BoolValue", GetType(Boolean)))

         ' Populate the table with sample values. When using custom paging,
         ' a query should only return enough data to fill a single page, 
         ' beginning at the start index.
         Dim i As Integer         

         For i = startIndex To ((startIndex + MyDataGrid.PageSize) - 1) 

             dr = dt.NewRow()

             dr(0) = i
             dr(1) = "Item " & i.ToString()
             dr(2) = DateTime.Now.ToShortDateString()
             If (i Mod 2 <> 0) Then
                dr(3) = True
             Else
                dr(3) = False
             End If

             dt.Rows.Add(dr)

         Next i

         Dim dv As DataView = New DataView(dt)
         Return dv

      End Function

      Sub Page_Load(sender As Object, e As EventArgs) 

         ' Load sample data only once, when the page is first loaded.
         If Not IsPostBack Then 

            ' Set the virtual item count, which specifies the total number
            ' items displayed in the DataGrid control when custom paging
            ' is used.
            MyDataGrid.VirtualItemCount = 200

            ' Retrieve the segment of data to display on the page from the 
            ' data source and bind it to the DataGrid control.
            BindGrid()

         End If

      End Sub

      Sub MyDataGrid_Page(sender as Object, e As DataGridPageChangedEventArgs) 

         ' For the DataGrid control to navigate to the correct page when
         ' paging is allowed, the CurrentPageIndex property must be updated
         ' programmatically. This process is usually accomplished in the
         ' event-handling method for the PageIndexChanged event.

         ' Set CurrentPageIndex to the page the user clicked.
         MyDataGrid.CurrentPageIndex = e.NewPageIndex

         ' Calculate the index of the first item to display on the page 
         ' using the current page index and the page size.
         startIndex = MyDataGrid.CurrentPageIndex * MyDataGrid.PageSize

         ' Retrieve the segment of data to display on the page from the 
         ' data source and bind it to the DataGrid control.
         BindGrid()

      End Sub

      Sub BindGrid() 

         MyDataGrid.DataSource = CreateDataSource()
         MyDataGrid.DataBind()

      End Sub

   </script>

<head runat="server">
    <title> DataGrid Custom Paging Example </title>
</head>
<body>

   <form id="form1" runat="server">

      <h3> DataGrid Custom Paging Example </h3>

      <asp:DataGrid id="MyDataGrid" 
           AllowCustomPaging="True" 
           AllowPaging="True" 
           PageSize="10" 
           OnPageIndexChanged="MyDataGrid_Page" 
           runat="server">

         <HeaderStyle BackColor="Navy" 
                      ForeColor="White" 
                      Font-Bold="True" />

         <PagerStyle Mode="NumericPages" 
                     HorizontalAlign="Right" />

      </asp:DataGrid>

   </form>

</body>
</html>

<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

<!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" >

   <script runat="server">

      // Normally, an entire data source is loaded in the DataGrid control, 
      // which can take up a lot of resources. This example uses custom 
      // paging, which loads only the segment of data needed to fill a
      // single page. In order to query for the appropriate segment of
      // data, the index of the first item displayed on a page must be
      // tracked as the user navigates between pages.
      int startIndex = 0;

      ICollection CreateDataSource() 
      {

         // Create sample data for the DataGrid control.
         DataTable dt = new DataTable();
         DataRow dr;

         // Define the columns of the table.
         dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
         dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
         dt.Columns.Add(new DataColumn("DateTimeValue", typeof(string)));
         dt.Columns.Add(new DataColumn("BoolValue", typeof(bool)));

         // Populate the table with sample values. When using custom paging,
         // a query should only return enough data to fill a single page, 
         // beginning at the start index.
         for (int i = startIndex; i < (startIndex + MyDataGrid.PageSize); i++) 
         {
             dr = dt.NewRow();

             dr[0] = i;
             dr[1] = "Item " + i.ToString();
             dr[2] = DateTime.Now.ToShortDateString();
             dr[3] = (i % 2 != 0) ? true : false;

             dt.Rows.Add(dr);
         }

         DataView dv = new DataView(dt);
         return dv;

      }

      void Page_Load(Object sender, EventArgs e) 
      {

         // Load sample data only once, when the page is first loaded.
         if (!IsPostBack) 
         {

            // Set the virtual item count, which specifies the total number
            // items displayed in the DataGrid control when custom paging
            // is used.
            MyDataGrid.VirtualItemCount = 200;

            // Retrieve the segment of data to display on the page from the
            // data source and bind it to the DataGrid control.
            BindGrid();

         }

      }

      void MyDataGrid_Page(Object sender, DataGridPageChangedEventArgs e) 
      {

         // For the DataGrid control to navigate to the correct page when
         // paging is allowed, the CurrentPageIndex property must be updated
         // programmatically. This process is usually accomplished in the
         // event-handling method for the PageIndexChanged event.

         // Set CurrentPageIndex to the page the user clicked.
         MyDataGrid.CurrentPageIndex = e.NewPageIndex;

         // Calculate the index of the first item to display on the page 
         // using the current page index and the page size.
         startIndex = MyDataGrid.CurrentPageIndex * MyDataGrid.PageSize;

         // Retrieve the segment of data to display on the page from the 
         // data source and bind it to the DataGrid control.
         BindGrid();

      }

      void BindGrid() 
      {

         MyDataGrid.DataSource = CreateDataSource();
         MyDataGrid.DataBind();

      }

   </script>

<head runat="server">
    <title> DataGrid Custom Paging Example </title>
</head>
<body>

   <form id="form1" runat="server">

      <h3> DataGrid Custom Paging Example </h3>

      <asp:DataGrid id="MyDataGrid" 
           AllowCustomPaging="True" 
           AllowPaging="True" 
           PageSize="10" 
           OnPageIndexChanged="MyDataGrid_Page" 
           runat="server">

         <HeaderStyle BackColor="Navy" 
                      ForeColor="White" 
                      Font-Bold="True" />

         <PagerStyle Mode="NumericPages" 
                     HorizontalAlign="Right" />

      </asp:DataGrid>

   </form>

</body>
</html>

DataGrid 控制項也提供了內建的排序能力。啟用排序時,LinkButton 控制項會呈現在每一資料行的行首,讓您能夠以選取的資料行排序 DataGrid。按一下 LinkButton 便會引發 SortCommand 事件。是否為事件處理常式提供程式碼,將由您決定。處理常式的基本邏輯是先排序清單,接下來再將資料重新繫結至 DataGrid。

下列範例示範如何在 DataGrid 控制項中使用排序。

<%@ Page Language="VB" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

 <!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" >
 <script language="VB" runat="server">

    Dim SortExpression As String

    Function CreateDataSource() As ICollection
        Dim dt As New DataTable()
        Dim dr As DataRow
        Dim Rand_Num As New Random()

        dt.Columns.Add(New DataColumn("IntegerValue", GetType(Int32)))
        dt.Columns.Add(New DataColumn("StringValue", GetType(String)))
        dt.Columns.Add(New DataColumn("CurrencyValue", GetType(Double)))

        Dim i As Integer
        For i = 0 To 14
            dr = dt.NewRow()

            dr(0) = i
            dr(1) = "Item " & i.ToString()
            dr(2) = 1.23 * Rand_Num.Next(1, 15)

            dt.Rows.Add(dr)
        Next i

        Dim dv As New DataView(dt)
        dv.Sort = SortExpression
        Return dv
    End Function 'CreateDataSource


    Sub Page_Load(sender As Object, e As EventArgs)

        If Not IsPostBack Then

            If SortExpression = "" Then
                SortExpression = "IntegerValue"
            End If
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End If
    End Sub 'Page_Load


    Sub Sort_Grid(sender As Object, e As DataGridSortCommandEventArgs)
        SortExpression = e.SortExpression.ToString()
        ItemsGrid.DataSource = CreateDataSource()
        ItemsGrid.DataBind()
    End Sub 'Sort_Grid

 </script>

 <head runat="server">
    <title>DataGrid Sorting Example</title>
</head>
<body>

    <form id="form1" runat="server">

       <h3>DataGrid Sorting Example</h3>

       <asp:DataGrid id="ItemsGrid" runat="server"
            BorderColor="black"
            BorderWidth="1"
            CellPadding="3"
            AllowSorting="true"
            OnSortCommand="Sort_Grid"
            HeaderStyle-BackColor="#00aaaa"
            AutoGenerateColumns="true"/>

    </form>

 </body>
 </html>

<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

 <!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" >
 <script language="C#" runat="server">

    string SortExpression;

    ICollection CreateDataSource() 
    {
       DataTable dt = new DataTable();
       DataRow dr;
       Random Rand_Num = new Random();

       dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
       dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
       dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));

       for (int i = 0; i < 15; i++) 
       {
          dr = dt.NewRow();

          dr[0] = i;
          dr[1] = "Item " + i.ToString();
          dr[2] = 1.23 * Rand_Num.Next(1, 15);

          dt.Rows.Add(dr);
       }

       DataView dv = new DataView(dt);
       dv.Sort=SortExpression;
       return dv;
    }

    void Page_Load(Object sender, EventArgs e) 
    {

       if (!IsPostBack) 
       {

          if (SortExpression == "")
             SortExpression = "IntegerValue";      
          ItemsGrid.DataSource = CreateDataSource();
          ItemsGrid.DataBind();
       }

    }

    void Sort_Grid(Object sender, DataGridSortCommandEventArgs e) 
    {
       SortExpression = e.SortExpression.ToString();
       ItemsGrid.DataSource = CreateDataSource();
       ItemsGrid.DataBind();
    }

 </script>

 <head runat="server">
    <title>DataGrid Sorting Example</title>
</head>
<body>

    <form id="form1" runat="server">

       <h3>DataGrid Sorting Example</h3>

       <asp:DataGrid id="ItemsGrid" runat="server"
            BorderColor="black"
            BorderWidth="1"
            CellPadding="3"
            AllowSorting="true"
            OnSortCommand="Sort_Grid"
            HeaderStyle-BackColor="#00aaaa"
            AutoGenerateColumns="true"/>

    </form>

 </body>
 </html>

<%@ Page Language="JScript" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

 <!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" >
 <script language="JScript" runat="server">

    var SortExpression : String;

    function CreateDataSource () : ICollection
    {
      var dt : DataTable = new DataTable();
      var dr : DataRow;
      var Rand_Num : Random = new Random();

      dt.Columns.Add(new DataColumn("IntegerValue", Int32));
      dt.Columns.Add(new DataColumn("StringValue", System.String));
      dt.Columns.Add(new DataColumn("CurrencyValue", double));

      for (var i : int = 0; i < 15; i++) 
      {
          dr = dt.NewRow();

          dr[0] = i;
          dr[1] = "Item " + i.ToString();
          dr[2] = 1.23 * Rand_Num.Next(1, 15);

          dt.Rows.Add(dr);
      }

      var dv : DataView = new DataView(dt);
      dv.Sort=SortExpression;
      return dv;
    }

    function Page_Load(sender, e : EventArgs) 
    {

       if (!IsPostBack) 
       {

          if (SortExpression == "")
             SortExpression = "IntegerValue";      
          ItemsGrid.DataSource = CreateDataSource();
          ItemsGrid.DataBind();
       }

    }

    function Sort_Grid(sender, e : DataGridSortCommandEventArgs) 
    {
       SortExpression = e.SortExpression.ToString();
       ItemsGrid.DataSource = CreateDataSource();
       ItemsGrid.DataBind();
    }

 </script>

 <head runat="server">
    <title>DataGrid Sorting Example</title>
</head>
<body>

    <form id="form1" runat="server">

       <h3>DataGrid Sorting Example</h3>

       <asp:DataGrid id="ItemsGrid" runat="server"
            BorderColor="black"
            BorderWidth="1"
            CellPadding="3"
            AllowSorting="true"
            OnSortCommand="Sort_Grid"
            HeaderStyle-BackColor="#00aaaa"
            AutoGenerateColumns="true"/>

    </form>

 </body>
 </html>

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>

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

<script runat="server">
    Function CreateDataSource() As ICollection
        ' Create a Random object to mix up the order 
        ' of items in the sample data.
        Dim randNum As Random = New Random()

        ' Create sample data for the DataGrid control.
        Dim dt As DataTable = New DataTable()

        ' Define the columns of the table.
        dt.Columns.Add( _
            New DataColumn("IntegerValue", GetType(Int32)))
        dt.Columns.Add( _
            New DataColumn("StringValue", GetType(String)))
        dt.Columns.Add( _
            New DataColumn("CurrencyValue", GetType(Double)))

        ' Populate the table with sample values.
        Dim i As Integer
        For i = 0 To 8
            Dim dr As DataRow = dt.NewRow()
            dr(0) = i
            dr(1) = "Item " & randNum.Next(1, 15).ToString()
            dr(2) = 1.23 * randNum.Next(1, 15)
            dt.Rows.Add(dr)
        Next

        ' Persist the data source between posts to 
        ' the server, in the session state.  
        Session("Source") = dt

        Dim dv As DataView = New DataView(dt)
        Return dv
    End Function

    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ' Load sample data when the page is first loaded.
        If Not IsPostBack Then
            ItemsGrid.DataSource = CreateDataSource()
            ItemsGrid.DataBind()
        End If
    End Sub

    Sub Sort_Grid(ByVal sender As Object, _
        ByVal e As DataGridSortCommandEventArgs)

        ' Retrieve the data source from session state.
        Dim dt As DataTable = _
            CType(Session("Source"), DataTable)

        ' Create a DataView from the DataTable.
        Dim dv As DataView = New DataView(dt)

        ' The DataView provides an easy way to 
        ' sort. Simply set the Sort property with 
        ' the name of the field to sort by.
        dv.Sort = e.SortExpression

        ' Rebind the data source and specify that 
        ' it should be sorted by the field specified 
        ' in the SortExpression property.
        ItemsGrid.DataSource = dv
        ItemsGrid.DataBind()
    End Sub

    Sub Check_Change(ByVal sender As Object, _
        ByVal e As EventArgs)
        ' Allow or prevent sorting depending 
        ' on the user's selection.
        ItemsGrid.AllowSorting = _
            AllowSortingCheckBox.Checked

        ' After changing the property, rebind 
        ' the data to refresh the DataGrid control.

        ' Retrieve data source from session state.
        Dim dt As DataTable = _
            CType(Session("Source"), DataTable)

        ' Create a DataView from the DataTable.
        Dim dv As DataView = New DataView(dt)

        ' Rebind the data source.
        ItemsGrid.DataSource = dv
        ItemsGrid.DataBind()
    End Sub
</script>

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

      <p>Select whether to allow sorting in the DataGrid control.<br />
      <asp:CheckBox id="AllowSortingCheckBox"
           Text="Allow sorting"
           AutoPostBack="True"
           Checked="True"
           OnCheckedChanged="Check_Change"
           runat="server"/></p>
      <hr />

      <b>Product List</b>
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           OnSortCommand="Sort_Grid"
           UseAccessibleHeader="true" 
           AutoGenerateColumns="False"
           AllowSorting="True"
           runat="server">

         <HeaderStyle BackColor="#00aaaa" />
         <Columns>
            <asp:BoundColumn DataField="IntegerValue" 
                 SortExpression="IntegerValue"
                 HeaderText="Item"/>

            <asp:BoundColumn DataField="StringValue"
                 SortExpression="StringValue" 
                 HeaderText="Description"/>

            <asp:BoundColumn DataField="CurrencyValue" 
                 HeaderText="Price"
                 SortExpression="CurrencyValue"
                 DataFormatString="{0:c}">

               <ItemStyle HorizontalAlign="Right">
               </ItemStyle>
            </asp:BoundColumn>
         </Columns> 
      </asp:DataGrid>

   </div>
   </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="True" %>
<%@ Import Namespace="System.Data" %>

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

<script runat="server">
    ICollection CreateDataSource()
    {
        // Create a Random object to mix up the 
        // order of items in the sample data.
        Random randNum = new Random();

        // Create sample data for the DataGrid control.
        DataTable dt = new DataTable();

        // Define the columns of the table.
        dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
        dt.Columns.Add(new DataColumn("StringValue", typeof(String)));
        dt.Columns.Add(new DataColumn("CurrencyValue", typeof(Double)));

        // Populate the table with sample values.
        for (int i = 0; i <= 8; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = "Item " + randNum.Next(1, 15).ToString();
            dr[2] = 1.23 * randNum.Next(1, 15);
            dt.Rows.Add(dr);
        }

        // To persist the data source between posts to the server,
        // store it in session state.  
        Session["Source"] = dt;
        DataView dv = new DataView(dt);
        return dv;
    }

    void Page_Load(Object sender, EventArgs e)
    {
        // Load sample data only once, when the page is first loaded.
        if (!IsPostBack)
        {
            ItemsGrid.DataSource = CreateDataSource();
            ItemsGrid.DataBind();
        }
    }

    void Sort_Grid(Object sender, DataGridSortCommandEventArgs e)
    {
        // Retrieve the data source from session state.
        DataTable dt = (DataTable)Session["Source"];

        // Create a DataView from the DataTable.
        DataView dv = new DataView(dt);

        // The DataView provides an easy way to sort. Simply set the
        // Sort property with the name of the field to sort by.
        dv.Sort = e.SortExpression;

        // Rebind the data source and specify that it should be sorted
        // by the field specified in the SortExpression property.
        ItemsGrid.DataSource = dv;
        ItemsGrid.DataBind();
    }

    void Check_Change(Object sender, EventArgs e)
    {
        // Allow or prevent sorting depending on the user's selection.
        ItemsGrid.AllowSorting = AllowSortingCheckBox.Checked;

        // After changing the property, rebind the data to
        // refresh the DataGrid control.

        // Retrieve the data source from session state.
        DataTable dt = (DataTable)Session["Source"];

        // Create a DataView from the DataTable.
        DataView dv = new DataView(dt);

        // Rebind the data source.
        ItemsGrid.DataSource = dv;
        ItemsGrid.DataBind();
    }
</script>

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

      <p>Select whether to allow sorting in the DataGrid control.<br />
      <asp:CheckBox id="AllowSortingCheckBox"
           Text="Allow sorting"
           AutoPostBack="True"
           Checked="True"
           OnCheckedChanged="Check_Change"
           runat="server"/></p>
      <hr />

      <b>Product List</b>
      <asp:DataGrid id="ItemsGrid"
           BorderColor="black"
           BorderWidth="1"
           CellPadding="3"
           OnSortCommand="Sort_Grid"
           UseAccessibleHeader="true"
           AutoGenerateColumns="False"
           AllowSorting="True"
           runat="server">

         <HeaderStyle BackColor="#00aaaa" />
         <Columns>
            <asp:BoundColumn DataField="IntegerValue" 
                 SortExpression="IntegerValue"
                 HeaderText="Item"/>

            <asp:BoundColumn DataField="StringValue"
                 SortExpression="StringValue" 
                 HeaderText="Description"/>

            <asp:BoundColumn DataField="CurrencyValue" 
                 HeaderText="Price"
                 SortExpression="CurrencyValue"
                 DataFormatString="{0:c}">

               <ItemStyle HorizontalAlign="Right">
               </ItemStyle>
            </asp:BoundColumn>
         </Columns> 
      </asp:DataGrid>

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

請參閱

參考

DataGrid

其他資源

Web 伺服器控制項語法