GridViewSortEventArgs Класс

Определение

Предоставляет данные о событии Sorting.

public ref class GridViewSortEventArgs : System::ComponentModel::CancelEventArgs
public class GridViewSortEventArgs : System.ComponentModel.CancelEventArgs
type GridViewSortEventArgs = class
    inherit CancelEventArgs
Public Class GridViewSortEventArgs
Inherits CancelEventArgs
Наследование
GridViewSortEventArgs

Примеры

В следующем примере показано, как использовать GridViewSortEventArgs объект, переданный методу обработки событий, для отмены операции сортировки, когда пользователь пытается отсортировать столбец адресов в элементе GridView управления .


<%@ 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_Sorting(Object sender, GridViewSortEventArgs e)
  {
    // Cancel the sorting operation if the user attempts
    // to sort by address.
    if (e.SortExpression == "Address")
    {
      e.Cancel = true;
      Message.Text = "You cannot sort by address.";
      SortInformationLabel.Text = "";
    }
    else
    {
      Message.Text = "";
    }
  }

  void CustomersGridView_Sorted(Object sender, EventArgs e)
  {
    // Display the sort expression and sort direction.
    SortInformationLabel.Text = "Sorting by " +
      CustomersGridView.SortExpression.ToString() +
      " in " + CustomersGridView.SortDirection.ToString() +
      " order.";
  }
  
</script>

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

      <asp:label id="Message"
        forecolor="Red"
        runat="server"/>
        
      <br/>
        
      <asp:label id="SortInformationLabel"
        forecolor="Navy"
        runat="server"/>
                
      <br/>  

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        autogeneratecolumns="true"
        allowpaging="true"
        emptydatatext="No data available." 
        allowsorting="true"
        onsorting="CustomersGridView_Sorting"
        onsorted="CustomersGridView_Sorted"  
        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">
<script runat="server">
  
  Sub CustomersGridView_Sorting(sender As Object, e As GridViewSortEventArgs)
  
    ' Cancel the sorting operation if the user attempts
    ' to sort by address.
    If e.SortExpression = "Address" Then
    
      e.Cancel = True
      Message.Text = "You cannot sort by address."
      SortInformationLabel.Text = ""
    
    Else
    
      Message.Text = ""
      
    End If
    
  End Sub

  Sub CustomersGridView_Sorted(ByVal sender As Object, ByVal e As EventArgs)
 
    ' Display the sort expression and sort direction.
    SortInformationLabel.Text = "Sorting by " & _
      CustomersGridView.SortExpression.ToString() & _
      " in " & CustomersGridView.SortDirection.ToString() & _
      " order."
    
  End Sub
    
</script>

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

      <asp:label id="Message"
        forecolor="Red"
        runat="server"/>
        
      <br/>
        
      <asp:label id="SortInformationLabel"
        forecolor="Navy"
        runat="server"/>
                
      <br/>  

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        autogeneratecolumns="true"
        allowpaging="true"
        emptydatatext="No data available." 
        allowsorting="true"
        onsorting="CustomersGridView_Sorting"
        onsorted="CustomersGridView_Sorted"  
        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>

Комментарии

Элемент GridView управления вызывает Sorting событие при нажатии кнопки Сортировка (кнопка со свойством CommandName "Сортировать"), но до того GridView , как элемент управления обработает операцию сортировки. Это позволяет предоставить метод обработки событий, который выполняет настраиваемую подпрограмму, например отмену операции сортировки, при каждом возникновении этого события.

Примечание

Хотя любая кнопка в элементе управления со свойством GridViewCommandName Sort вызывает Sorting событие , кнопки Сортировки обычно отображаются в строке заголовка GridView элемента управления.

Объект GridViewSortEventArgs передается методу обработки событий, который позволяет указать или определить выражение сортировки и направление сортировки GridView , в котором сортируется элемент управления . Чтобы определить выражение сортировки, используйте SortExpression свойство . Чтобы определить направление сортировки, используйте SortDirection свойство . Можно также отменить операцию сортировки, задав для Cancel свойства значение true.

Дополнительные сведения об обработке событий см. в разделе Обработка и вызов событий.

Список начальных значений свойств для экземпляра GridViewSortEventArgsсм. в конструкторе GridViewSelectEventArgs .

Конструкторы

GridViewSortEventArgs(String, SortDirection)

Инициализирует новый экземпляр класса GridViewSortEventArgs.

Свойства

Cancel

Возвращает или задает значение, показывающее, следует ли отменить событие.

(Унаследовано от CancelEventArgs)
SortDirection

Получает или задает направление сортировки в элементе управления GridView.

SortExpression

Получает или задает выражение, используемое для сортировки элементов в элементе управления GridView.

Методы

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к

См. также раздел