GridView.Sorting 이벤트
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
열을 정렬하는 하이퍼링크를 클릭하면 GridView 컨트롤이 정렬 작업을 처리하기 전에 이 이벤트가 발생합니다.
public:
event System::Web::UI::WebControls::GridViewSortEventHandler ^ Sorting;
public event System.Web.UI.WebControls.GridViewSortEventHandler Sorting;
member this.Sorting : System.Web.UI.WebControls.GridViewSortEventHandler
Public Custom Event Sorting As GridViewSortEventHandler
이벤트 유형
예제
다음 예제에서는 사용 하는 방법에 설명 합니다 속성을 프로그래밍 방식으로 설정 하 여 Sorting 개체에 GridView 바인딩된 경우 정렬 기능을 수행 하는 DataTable 이벤트 DataSource 입니다.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = Session["TaskTable"] as DataTable;
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
TaskGridView.DataSource = Session["TaskTable"];
TaskGridView.DataBind();
}
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Create a new table.
DataTable taskTable = new DataTable("TaskList");
// Create the columns.
taskTable.Columns.Add("Id", typeof(int));
taskTable.Columns.Add("Description", typeof(string));
//Add data to the new table.
for (int i = 0; i < 10; i++)
{
DataRow tableRow = taskTable.NewRow();
tableRow["Id"] = i;
tableRow["Description"] = "Task " + (10 - i).ToString();
taskTable.Rows.Add(tableRow);
}
//Persist the table in the Session object.
Session["TaskTable"] = taskTable;
//Bind the GridView control to the data source.
TaskGridView.DataSource = Session["TaskTable"];
TaskGridView.DataBind();
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sorting example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="TaskGridView" runat="server"
AllowSorting="true"
OnSorting="TaskGridView_Sorting" >
</asp:GridView>
</div>
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Protected Sub TaskGridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
'Retrieve the table from the session object.
Dim dt = TryCast(Session("TaskTable"), DataTable)
If dt IsNot Nothing Then
'Sort the data.
dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
TaskGridView.DataSource = Session("TaskTable")
TaskGridView.DataBind()
End If
End Sub
Private Function GetSortDirection(ByVal column As String) As String
' By default, set the sort direction to ascending.
Dim sortDirection = "ASC"
' Retrieve the last column that was sorted.
Dim sortExpression = TryCast(ViewState("SortExpression"), String)
If sortExpression IsNot Nothing Then
' Check if the same column is being sorted.
' Otherwise, the default value can be returned.
If sortExpression = column Then
Dim lastDirection = TryCast(ViewState("SortDirection"), String)
If lastDirection IsNot Nothing _
AndAlso lastDirection = "ASC" Then
sortDirection = "DESC"
End If
End If
End If
' Save new values in ViewState.
ViewState("SortDirection") = sortDirection
ViewState("SortExpression") = column
Return sortDirection
End Function
Protected Sub Page_Load()
If Not Page.IsPostBack Then
' Create a new table.
Dim taskTable As New DataTable("TaskList")
' Create the columns.
taskTable.Columns.Add("Id", GetType(Integer))
taskTable.Columns.Add("Description", GetType(String))
'Add data to the new table.
For i = 0 To 9
Dim tableRow As DataRow = taskTable.NewRow()
tableRow("Id") = i
tableRow("Description") = "Task " & (10 - i)
taskTable.Rows.Add(tableRow)
Next i
'Persist the table in the Session object.
Session("TaskTable") = taskTable
'Bind the GridView control to the data source.
TaskGridView.DataSource = Session("TaskTable")
TaskGridView.DataBind()
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sorting example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="TaskGridView" runat="server"
AllowSorting="true"
OnSorting="TaskGridView_Sorting" >
</asp:GridView>
</div>
</form>
</body>
</html>
다음 예제에서는 이벤트를 사용하여 Sorting 정렬 작업을 취소하는 방법을 보여 줍니다.
<%@ 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>
설명
합니다 Sorting 열을 정렬 하는 하이퍼링크를 클릭 하면 하기 전에 이벤트가 발생 된 GridView 컨트롤이 정렬 작업을 처리 합니다. 이렇게 하면 이 이벤트가 발생할 때마다 정렬 작업 취소와 같은 사용자 지정 루틴을 수행하는 이벤트 처리 메서드를 제공할 수 있습니다.
GridViewSortEventArgs 개체가 이벤트 처리 메서드에 전달되므로 열의 정렬 식을 확인하고 선택 작업을 취소해야 함을 나타낼 수 있습니다. 선택 작업을 취소 하려면 합니다 Cancel 의 속성을 GridViewSortEventArgs 개체를 true
입니다.
프로그래밍 방식으로 정렬 작업을 시작하는 방법에 대한 자세한 내용은 메서드를 Sort 참조하세요.
이벤트를 처리 하는 방법에 대 한 자세한 내용은 참조 하세요. 이벤트 처리 및 발생합니다.
적용 대상
추가 정보
.NET