GridView字段排序

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值