GridView.AllowSorting 속성

정의

정렬 기능을 사용할지 여부를 나타내는 값을 가져오거나 설정합니다.

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

속성 값

정렬 기능을 사용할 수 있으면 true이고, 그렇지 않으면 false입니다. 기본값은 false입니다.

예제

다음 예제에서는 사용 하는 AllowSorting 방법에 설명 합니다 자동으로 생성 된 열을 사용할 때 컨트롤에서 정렬을 GridView 사용 하도록 설정 하는 속성입니다.


<%@ 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 경우는 컬렉션이 정의 된 컨트롤 Columns 입니다. 정렬 방향을 나타내기 위해 정렬되는 열의 머리글에도 이미지가 프로그래밍 방식으로 추가됩니다. 이 샘플이 작동하려면 고유한 이미지를 제공해야 합니다.


<%@ 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 바인딩된 경우 컨트롤은 데이터 원본 컨트롤의 기능을 활용하고 자동 정렬 기능을 제공할 수 있습니다. 컨트롤이 GridView 프로그래밍 방식으로 속성을 설정 DataSource 하여 데이터 원본에 바인딩되는 경우 이벤트를 사용하여 Sorting 정렬 기능을 제공해야 합니다.

참고

데이터 원본에 따라 정렬 기능을 사용하도록 설정하기 위한 요구 사항이 다릅니다. 요구 사항을 확인하려면 특정 데이터 원본에 대한 설명서를 참조하세요.

정렬을 사용하려면 속성을 trueAllowSorting 설정합니다. 정렬을 사용하도록 설정하면 속성이 설정된 각 열 필드 SortExpression 의 제목 텍스트가 링크 단추로 표시됩니다.

참고

SortExpression 자동으로 생성된 열 필드의 속성이 자동으로 채워집니다. 컬렉션을 통해 Columns 고유한 열을 정의하는 경우 각 열에 SortExpression 대한 속성을 설정해야 합니다. 그렇지 않으면 열에 머리글에 링크 단추가 표시되지 않습니다.

열에 대한 링크 단추를 클릭하면 컨트롤의 GridView 항목이 정렬 식에 따라 정렬됩니다. 일반적으로 정렬 식은 단순히 열에 표시된 필드의 이름이므로 컨트롤이 GridView 해당 열과 관련하여 정렬됩니다. 여러 필드를 기준으로 정렬하려면 쉼표로 구분된 필드 이름 목록이 포함된 정렬 식을 사용합니다. 속성을 사용하여 SortExpression 컨트롤이 GridView 적용되는 정렬 식을 확인할 수 있습니다. 열의 링크 단추를 클릭하면 오름차순과 내림차순 사이의 정렬 방향이 반복적으로 전환됩니다. 현재 정렬 방향을 확인 하려면 사용 된 SortDirection 속성입니다.

컨트롤은 GridView 정렬이 발생할 때 사용자 지정 작업을 수행하는 데 사용할 수 있는 여러 이벤트를 제공합니다. 다음 표에서는 사용 가능한 이벤트를 나열합니다.

이벤트 설명
Sorted 열을 정렬하는 하이퍼링크를 클릭하면 GridView 컨트롤이 정렬 작업을 처리한 후에 이 이벤트가 발생합니다. 이 이벤트는 일반적으로 사용자가 하이퍼링크를 클릭하여 열을 정렬한 후 작업을 수행하는 데 사용됩니다.
Sorting 열을 정렬하는 하이퍼링크를 클릭하면 GridView 컨트롤이 정렬 작업을 처리하기 전에 이 이벤트가 발생합니다. 이 이벤트는 정렬 작업을 취소하거나 사용자 지정 정렬 루틴을 수행하는 데 자주 사용됩니다.

적용 대상

추가 정보