GridView.AllowSorting Proprietà

Definizione

Ottiene o imposta un valore che indica se la funzionalità di ordinamento è abilitata.

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. Il valore predefinito è false.

Esempio

Nell'esempio seguente viene illustrato come utilizzare la proprietà per abilitare l'ordinamento AllowSorting in un GridView controllo quando vengono utilizzate colonne generate automaticamente.


<%@ 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 proprietà per abilitare l'ordinamento AllowSorting in un GridView controllo quando viene definita una Columns raccolta. Un'immagine viene aggiunta anche a livello di codice all'intestazione della colonna ordinata per indicare la direzione di ordinamento. È necessario specificare immagini personalizzate per il funzionamento di questo esempio.


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

Nota

Le origini dati diverse hanno requisiti diversi per abilitare le funzionalità di ordinamento. Per determinare i requisiti, vedere la documentazione relativa all'origine dati specifica.

Per abilitare l'ordinamento, impostare la AllowSorting proprietà su true. Quando l'ordinamento è abilitato, il testo dell'intestazione per ogni campo di colonna con il relativo SortExpression set di proprietà viene visualizzato come pulsante di collegamento.

Nota

La SortExpression proprietà per un campo delle colonne generate automaticamente viene popolata automaticamente. Se si definiscono colonne personalizzate tramite l'insieme Columns , è necessario impostare la SortExpression proprietà per ogni colonna. In caso contrario, la colonna non visualizzerà il pulsante di collegamento nell'intestazione.

Se si fa clic sul pulsante di collegamento per una colonna, gli elementi del GridView controllo vengono ordinati in base all'espressione di ordinamento. In genere, l'espressione di ordinamento è semplicemente il nome del campo visualizzato nella colonna, che determina l'ordinamento del GridView controllo rispetto a tale colonna. Per ordinare in base a più campi, usare un'espressione di ordinamento contenente un elenco delimitato da virgole di nomi di campo. È possibile determinare l'espressione di ordinamento applicata dal GridView controllo utilizzando la SortExpression proprietà . Se si fa clic sul pulsante di collegamento di una colonna, viene attivata ripetutamente la direzione di ordinamento tra l'ordine crescente e quello decrescente. Per determinare la direzione di ordinamento corrente, utilizzare la SortDirection proprietà .

Il GridView controllo fornisce diversi eventi che è possibile usare per eseguire un'azione personalizzata quando si verifica l'ordinamento. Nella tabella seguente sono elencati gli eventi disponibili.

Event Descrizione
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. Questo evento viene comunemente usato per eseguire un'attività dopo che l'utente fa clic su un collegamento ipertestuale per ordinare una colonna.
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. Questo evento viene spesso utilizzato per annullare l'operazione di ordinamento o per eseguire una routine di ordinamento personalizzata.

Si applica a

Vedi anche