GridView.AllowSorting GridView.AllowSorting GridView.AllowSorting GridView.AllowSorting Property

Definizione

Ottiene o imposta un valore che indica se la funzionalità di ordinamento è abilitata.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

Valore della proprietà

true se la funzionalità di ordinamento è abilitata, altrimenti false.true if the sorting feature is enabled; otherwise, false. Il valore predefinito è false.The default is false.

Esempi

Nell'esempio seguente viene illustrato come utilizzare la AllowSorting proprietà per abilitare l'ordinamento in un GridView controllo quando vengono utilizzate colonne generate automaticamente.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>

Nell'esempio seguente viene illustrato come utilizzare la AllowSorting proprietà per abilitare l'ordinamento in un GridView controllo quando viene Columns definita una raccolta.The following example demonstrates how to use the AllowSorting property to enable sorting in a GridView control when a Columns collection is defined. Un'immagine viene inoltre aggiunta a livello di codice all'intestazione della colonna da ordinare per indicare la direzione di ordinamento.An image is also programmatically added to the header of the column being sorted to indicate the sort direction. Per il corretto funzionamento di questo esempio, è necessario fornire immagini personalizzate.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>

Commenti

Quando un controllo origine dati che supporta l'ordinamento è associato GridView al controllo, il GridView controllo può sfruttare le funzionalità del controllo origine dati e fornire funzionalità di ordinamento automatico.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. Quando il GridView controllo è associato a un'origine dati impostando la DataSource proprietà a livello di codice, è necessario fornire la funzionalità di ordinamento utilizzando Sorting l'evento.When 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.

Nota

Origini dati diverse hanno requisiti diversi per l'abilitazione delle funzionalità di ordinamento.Different data sources have different requirements for enabling their sorting capabilities. Per determinare i requisiti, vedere la documentazione per l'origine dati specifica.To determine the requirements, see the documentation for the specific data source.

Per abilitare l'ordinamento, impostare la AllowSorting proprietà su true.To enable sorting, set the AllowSorting property to true. Quando l'ordinamento è abilitato, il testo dell'intestazione per ogni campo colonna con SortExpression il relativo set di proprietà viene visualizzato come pulsante di collegamento.When sorting is enabled, the heading text for each column field with its SortExpression property set is displayed as a link button.

Nota

La SortExpression proprietà per un campo colonne generato automaticamente viene popolata automaticamente.The SortExpression property for an automatically generated columns field is automatically populated. Se si definiscono colonne personalizzate tramite la Columns raccolta, è necessario impostare la SortExpression proprietà per ogni colonna. in caso contrario, la colonna non visualizzerà il pulsante di collegamento nell'intestazione.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.

Quando si fa clic sul pulsante di collegamento per una colonna, GridView gli elementi del controllo vengono ordinati in base all'espressione di ordinamento.Clicking the link button for a column causes the items in the GridView control to be sorted based on the sort expression. In genere, l'espressione di ordinamento è semplicemente il nome del campo visualizzato nella colonna, che determina l' GridView ordinamento del controllo rispetto a tale colonna.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. Per eseguire l'ordinamento in base a più campi, utilizzare un'espressione di ordinamento che contenga un elenco delimitato da virgole di nomi di campo.To sort by multiple fields, use a sort expression that contains a comma-separated list of field names. È possibile determinare l'espressione di ordinamento che GridView il controllo sta applicando utilizzando SortExpression la proprietà.You can determine the sort expression that the GridView control is applying by using the SortExpression property. Se si fa clic sul pulsante di collegamento di una colonna, la direzione di ordinamento viene alternata in ordine crescente e decrescente.Clicking a column's link button repeatedly toggles the sort direction between ascending and descending order. Per determinare la direzione di ordinamento corrente, usare SortDirection la proprietà.To determine the current sort direction, use the SortDirection property.

Il GridView controllo fornisce diversi eventi che è possibile utilizzare per eseguire un'azione personalizzata quando si verifica l'ordinamento.The GridView control provides several events that you can use to perform a custom action when sorting occurs. Nella tabella seguente sono elencati gli eventi disponibili.The following table lists the available events.

eventEvent DescriptionDescription
Sorted Si verifica quando viene fatto clic sul collegamento ipertestuale per l'ordinamento di una colonna, ma dopo che il controllo GridView ha gestito l'operazione di ordinamento.Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. Questo evento viene comunemente usato per eseguire un'attività dopo che l'utente fa clic su un collegamento ipertestuale per ordinare una colonna.This event is commonly used to perform a task after the user clicks a hyperlink to sort a column.
Sorting Si verifica quando viene fatto clic sul collegamento ipertestuale per l'ordinamento di una colonna, ma prima che il controllo GridView gestisca l'operazione di ordinamento.Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation. Questo evento viene spesso utilizzato per annullare l'operazione di ordinamento o per eseguire una routine di ordinamento personalizzata.This event is often used to cancel the sorting operation or to perform a custom sorting routine.

Si applica a

Vedi anche