GridView.AllowSorting Propiedad

Definición

Obtiene o establece un valor que indica si la característica de ordenación está habilitada.

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

Valor de propiedad

Es true si está habilitada la característica de ordenación; en caso contrario, es false. De manera predeterminada, es false.

Ejemplos

En el ejemplo siguiente se muestra cómo usar la propiedad para habilitar la AllowSorting ordenación en un GridView control cuando se usan columnas generadas automáticamente.


<%@ 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>

En el ejemplo siguiente se muestra cómo usar la propiedad para habilitar la AllowSorting ordenación en un GridView control cuando se define una Columns colección. Una imagen también se agrega mediante programación al encabezado de la columna que se ordena para indicar la dirección de ordenación. Debe proporcionar sus propias imágenes para que este ejemplo funcione.


<%@ 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>

Comentarios

Cuando un control de origen de datos que admite la ordenación está enlazado al GridView control, el GridView control puede aprovechar las funcionalidades del control de origen de datos y proporcionar funcionalidad de ordenación automática. Cuando el GridView control se enlaza a un origen de datos estableciendo la DataSource propiedad mediante programación, debe proporcionar la funcionalidad de ordenación mediante el Sorting evento .

Nota

Los distintos orígenes de datos tienen requisitos diferentes para habilitar sus funcionalidades de ordenación. Para determinar los requisitos, consulte la documentación del origen de datos específico.

Para habilitar la ordenación, establezca la AllowSorting propiedad en true. Cuando la ordenación está habilitada, el texto del encabezado de cada campo de columna con su SortExpression conjunto de propiedades se muestra como un botón de vínculo.

Nota

La SortExpression propiedad de un campo de columnas generada automáticamente se rellena automáticamente. Si define sus propias columnas a través de la Columns colección, debe establecer la SortExpression propiedad para cada columna; de lo contrario, la columna no mostrará el botón de vínculo en el encabezado.

Al hacer clic en el botón de vínculo de una columna, los elementos del GridView control se ordenarán en función de la expresión de ordenación. Normalmente, la expresión de ordenación es simplemente el nombre del campo que se muestra en la columna, lo que hace que el GridView control se ordene con respecto a esa columna. Para ordenar por varios campos, use una expresión de ordenación que contenga una lista separada por comas de nombres de campo. Puede determinar la expresión de ordenación que el GridView control está aplicando mediante la SortExpression propiedad . Al hacer clic en el botón de vínculo de una columna repetidamente, se alterna la dirección de ordenación entre orden ascendente y descendente. Para determinar la dirección de ordenación actual, use la SortDirection propiedad .

El GridView control proporciona varios eventos que puede usar para realizar una acción personalizada cuando se produce la ordenación. En la tabla siguiente se enumeran los eventos disponibles.

Evento Descripción
Sorted Se produce cuando se hace clic en el hipervínculo para ordenar una columna, pero después de que el control GridView se ocupe de la operación de ordenación. Este evento se usa normalmente para realizar una tarea después de que el usuario haga clic en un hipervínculo para ordenar una columna.
Sorting Se produce cuando se hace clic en el hipervínculo para ordenar una columna, pero antes de que el control GridView se ocupe de la operación de ordenación. Este evento se suele usar para cancelar la operación de ordenación o para realizar una rutina de ordenación personalizada.

Se aplica a

Consulte también