GridView.AllowSorting 屬性

定義

取得或設定值,指出是否啟用排序功能。Gets or sets a value indicating whether the sorting feature is enabled.

public:
 virtual property bool AllowSorting { bool get(); void set(bool value); };
public virtual bool AllowSorting { get; set; }
member this.AllowSorting : bool with get, set
Public Overridable Property AllowSorting As Boolean

屬性值

Boolean

如果啟用排序功能則為 true,否則為 falsetrue if the sorting feature is enabled; otherwise, false. 預設為 falseThe default is false.

範例

下列範例示範如何在 AllowSorting GridView 使用自動產生的資料行時,使用屬性來啟用控制項中的排序。The following example demonstrates how to use the AllowSorting property to enable sorting in a GridView control when automatically generated columns are used.


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView AllowSorting Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView AllowSorting Example</h3>

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        autogeneratecolumns="true"
        emptydatatext="No data available." 
        allowsorting="true" 
        runat="server">
                
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
        
    </form>
  </body>
</html>


<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
    <title>GridView AllowSorting Example</title>
</head>
<body>
    <form id="form1" runat="server">
        
      <h3>GridView AllowSorting Example</h3>

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        autogeneratecolumns="true"
        emptydatatext="No data available." 
        allowsorting="true" 
        runat="server">
                
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
        
    </form>
  </body>
</html>

下列範例示範如何在 AllowSorting GridView 定義集合時,使用屬性來啟用控制項中的排序 ColumnsThe following example demonstrates how to use the AllowSorting property to enable sorting in a GridView control when a Columns collection is defined. 影像也會以程式設計的方式加入至要排序之資料行的標頭,以指出排序方向。An image is also programmatically added to the header of the column being sorted to indicate the sort direction. 您必須提供自己的映射,此範例才能運作。You must provide your own images for this sample to work.


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

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

  void CustomersGridView_RowCreated(Object sender, GridViewRowEventArgs e)
  {
    
    // Use the RowType property to determine whether the 
    // row being created is the header row. 
    if (e.Row.RowType == DataControlRowType.Header)
    {
      // Call the GetSortColumnIndex helper method to determine
      // the index of the column being sorted.
      int sortColumnIndex = GetSortColumnIndex();
      
      if (sortColumnIndex != -1)
      {
        // Call the AddSortImage helper method to add
        // a sort direction image to the appropriate
        // column header. 
        AddSortImage(sortColumnIndex, e.Row);
      }
    }
  }

  // This is a helper method used to determine the index of the
  // column being sorted. If no column is being sorted, -1 is returned.
  int GetSortColumnIndex()
  {

    // Iterate through the Columns collection to determine the index
    // of the column being sorted.
    foreach (DataControlField field in CustomersGridView.Columns)
    {
      if (field.SortExpression == CustomersGridView.SortExpression)
      {
        return CustomersGridView.Columns.IndexOf(field);
      }
    }

    return -1;
  }

  // This is a helper method used to add a sort direction
  // image to the header of the column being sorted.
  void AddSortImage(int columnIndex, GridViewRow headerRow)
  {
    
    // Create the sorting image based on the sort direction.
    Image sortImage = new Image();
    if (CustomersGridView.SortDirection == SortDirection.Ascending)
    {
      sortImage.ImageUrl = "~/Images/Ascending.jpg";
      sortImage.AlternateText = "Ascending Order";
    }
    else
    {
      sortImage.ImageUrl = "~/Images/Descending.jpg";
      sortImage.AlternateText = "Descending Order";
    }

    // Add the image to the appropriate header cell.
    headerRow.Cells[columnIndex].Controls.Add(sortImage);
    
  }
    
</script>

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

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        autogeneratecolumns="false"
        emptydatatext="No data available." 
        allowsorting="true"
        onrowcreated="CustomersGridView_RowCreated"
        runat="server">
        
        <columns>
          <asp:boundfield datafield="CustomerID"
            headertext="Customer ID"
            headerstyle-wrap="false" 
            sortexpression="CustomerID"/>
          <asp:boundfield datafield="CompanyName"
            headertext="CompanyName"
            headerstyle-wrap="false"
            sortexpression="CompanyName"/>
          <asp:boundfield datafield="Address"
            headertext="Address"
            headerstyle-wrap="false"
            sortexpression="Address"/>
          <asp:boundfield datafield="City"
            headertext="City"
            headerstyle-wrap="false"
            sortexpression="City"/>
          <asp:boundfield datafield="PostalCode"
            headertext="Postal Code"
            headerstyle-wrap="false"
            sortexpression="PostalCode" />
          <asp:boundfield datafield="Country"
            headertext="Country"
            headerstyle-wrap="false"
            sortexpression="Country"/>         
        </columns>
                
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
        
    </form>
  </body>
</html>


<%@ Page language="VB" %>

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

  Sub CustomersGridView_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    
    ' Use the RowType property to determine whether the 
    ' row being created is the header row. 
    If e.Row.RowType = DataControlRowType.Header Then
    
      ' Call the GetSortColumnIndex helper method to determine
      ' the index of the column being sorted.
      Dim sortColumnIndex As Integer = GetSortColumnIndex()
      
      If sortColumnIndex <> -1 Then
      
        ' Call the AddSortImage helper method to add
        ' a sort direction image to the appropriate
        ' column header. 
        AddSortImage(sortColumnIndex, e.Row)
    
      End If
      
    End If
    
  End Sub

  ' This is a helper method used to determine the index of the
  ' column being sorted. If no column is being sorted, -1 is returned.
  Function GetSortColumnIndex() As Integer

    ' Iterate through the Columns collection to determine the index
    ' of the column being sorted.
    Dim field As DataControlField
    For Each field In CustomersGridView.Columns
    
      If field.SortExpression = CustomersGridView.SortExpression Then
      
        Return CustomersGridView.Columns.IndexOf(field)

      End If
      
    Next

    Return -1
      
  End Function

  ' This is a helper method used to add a sort direction
  ' image to the header of the column being sorted.
  Sub AddSortImage(ByVal columnIndex As Integer, ByVal row As GridViewRow)

    ' Create the sorting image based on the sort direction.
    Dim sortImage As New Image()
    If CustomersGridView.SortDirection = SortDirection.Ascending Then
    
      sortImage.ImageUrl = "~/Images/Ascending.jpg"
      sortImage.AlternateText = "Ascending Order"
    
    Else
    
      sortImage.ImageUrl = "~/Images/Descending.jpg"
      sortImage.AlternateText = "Descending Order"
    
    End If
    ' Add the image to the appropriate header cell.
    row.Cells(columnIndex).Controls.Add(sortImage)
    
  End Sub
    
</script>

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

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        autogeneratecolumns="false"
        emptydatatext="No data available." 
        allowsorting="true"
        onrowcreated="CustomersGridView_RowCreated"
        runat="server">
        
        <columns>
          <asp:boundfield datafield="CustomerID"
            headertext="Customer ID"
            headerstyle-wrap="false" 
            sortexpression="CustomerID"/>
          <asp:boundfield datafield="CompanyName"
            headertext="CompanyName"
            headerstyle-wrap="false"
            sortexpression="CompanyName"/>
          <asp:boundfield datafield="Address"
            headertext="Address"
            headerstyle-wrap="false"
            sortexpression="Address"/>
          <asp:boundfield datafield="City"
            headertext="City"
            headerstyle-wrap="false"
            sortexpression="City"/>
          <asp:boundfield datafield="PostalCode"
            headertext="Postal Code"
            headerstyle-wrap="false"
            sortexpression="PostalCode" />
          <asp:boundfield datafield="Country"
            headertext="Country"
            headerstyle-wrap="false"
            sortexpression="Country"/>         
        </columns>
                
      </asp:gridview>
            
      <!-- This example uses Microsoft SQL Server and connects  -->
      <!-- to the Northwind sample database. Use an ASP.NET     -->
      <!-- expression to retrieve the connection string value   -->
      <!-- from the Web.config file.                            -->
      <asp:sqldatasource id="CustomersSource"
        selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
        connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>" 
        runat="server"/>
        
    </form>
  </body>
</html>

備註

當支援排序的資料來源控制項系結至控制項時 GridViewGridView 控制項可以利用資料來源控制項的功能,並提供自動排序功能。When a data source control that supports sorting is bound to the GridView control, the GridView control can take advantage of the data source control's capabilities and provide automatic sorting functionality. GridView以程式設計方式設定屬性,將控制項系結至資料來源時 DataSource ,您必須使用事件提供排序功能 SortingWhen the GridView control is bound to a data source by setting the DataSource property programmatically, you must provide the sorting functionality by using the Sorting event.

注意

不同的資料來源有不同的需求來啟用其排序功能。Different data sources have different requirements for enabling their sorting capabilities. 若要判斷需求,請參閱特定資料來源的檔。To determine the requirements, see the documentation for the specific data source.

若要啟用排序,請將 AllowSorting 屬性設定為 trueTo enable sorting, set the AllowSorting property to true. 啟用排序時,會將每個資料列欄位的標題文字 SortExpression 顯示為其屬性集,並顯示為 [連結] 按鈕。When sorting is enabled, the heading text for each column field with its SortExpression property set is displayed as a link button.

注意

自動 SortExpression 產生的資料列欄位的屬性會自動填入。The SortExpression property for an automatically generated columns field is automatically populated. 如果您透過集合定義您自己的資料行 Columns ,則必須設定 SortExpression 每個資料行的屬性,否則資料行不會在標頭中顯示連結按鈕。If you define your own columns through the Columns collection, you must set the SortExpression property for each column; otherwise, the column will not display the link button in the header.

按一下資料行的連結按鈕, GridView 就會根據排序運算式來排序控制項中的專案。Clicking the link button for a column causes the items in the GridView control to be sorted based on the sort expression. 通常,排序運算式只是資料行中所顯示之欄位的名稱,這會讓 GridView 控制項根據該資料行進行排序。Typically, the sort expression is simply the name of the field displayed in the column, which causes the GridView control to sort with respect to that column. 若要依多個欄位排序,請使用排序運算式,其中包含以逗號分隔的功能變數名稱清單。To sort by multiple fields, use a sort expression that contains a comma-separated list of field names. 您可以使用屬性來判斷控制項所套用的排序運算式 GridView SortExpressionYou can determine the sort expression that the GridView control is applying by using the SortExpression property. 按一下資料行的連結按鈕,就會重複切換昇冪和遞減順序之間的排序方向。Clicking a column's link button repeatedly toggles the sort direction between ascending and descending order. 若要判斷目前的排序方向,請使用 SortDirection 屬性。To determine the current sort direction, use the SortDirection property.

GridView控制項提供數個事件,可讓您在排序發生時用來執行自訂動作。The GridView control provides several events that you can use to perform a custom action when sorting occurs. 下表列出可用的事件。The following table lists the available events.

事件Event 描述Description
Sorted 按一下排序資料行的超連結時發生 (但在 GridView 控制項處理排序作業之後)。Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. 這個事件通常是在使用者按一下超連結來排序資料行之後,用來執行工作。This event is commonly used to perform a task after the user clicks a hyperlink to sort a column.
Sorting 按一下排序資料行的超連結時發生 (但在 GridView 控制項處理排序作業之前)。Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation. 此事件通常用來取消排序作業,或執行自訂排序常式。This event is often used to cancel the sorting operation or to perform a custom sorting routine.

適用於

另請參閱