<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.Data" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["SortExpression"] = "ID";//第一次加载时,默认按ID排序
ViewState["SortDir"] = "ASC";//排序方式为升序
DBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//首先判断当前的排序表达式(字段),是否为当前当前的表达式。。。
if (ViewState["SortExpression"].ToString() == e.SortExpression.ToString())
{
//判断当前的排序方式是否为倒序(DESC),如果是则将排序方式设为升序(ASC),原因是:因为我们要做双向排序!
if (ViewState["SortDir"].ToString() == "DESC")
{
ViewState["SortDir"] = "ASC";
}
else
{
ViewState["SortDir"] = "DESC";
}
}
else
{
ViewState["SortExpression"] = e.SortExpression; //将触发到表达式赋值给ViewState["SortExpression"];
}
DBind();
}
protected static DataTable CreateTable()
{
DataTable dt = new DataTable("DtName");
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Random");
DataRow dr;
Random rd = new Random();
for (int i = 0; i < 30; i++)
{
dr = dt.NewRow();
dr["ID"] = i;
dr["Name"] = "Item" + i.ToString();
dr["Random"] = 1.23 * rd.Next(20);
dt.Rows.Add(dr);
}
return dt; //返回一个DataTable的数据集
}
private void DBind()
{
DataView dv = new DataView(CreateTable());
dv.Sort = (string)ViewState["SortExpression"] + " " + ViewState["SortDir"].ToString(); //设置数据源的排序表达式
this.GridView1.DataSource = dv;
this.GridView1.DataBind();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>双向排序(ASC & DESC)</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" OnSorting="GridView1_Sorting" AllowSorting="True">
</asp:GridView>
</div>
</form>
</body>
</html>
转载于:https://www.cnblogs.com/nyth/archive/2011/03/24/1993536.html