gridview自动排序示例分享

示例如下:前台

复制代码 代码如下:


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>无标题页</title>
</head>
<body>
    <form runat="server">
    <div>
        <asp:GridView runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AllowSorting="True" OnSorting="GridView1_Sorting">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="id" HeaderText="ID" SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="NAME" SortExpression="name" />
                <asp:BoundField DataField="age" HeaderText="AGE" SortExpression="age" />
            </Columns>
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

前台注意点:
需要对GridView启用AllowSorting、设置OnSorting事件,对需要排序的列设定SortExpression属性。

后台

复制代码 代码如下:


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // 设定初始排序参数值

// 错误的属性设置方法:SortExpression、SortDirection均是GridView只读属性,无法直接赋值。
            //this.GridView1.SortExpression = "id";
            //this.GridView1.SortDirection = "ASC";

// 正确的属性设置方法
            this.GridView1.Attributes.Add("SortExpression", "id");
            this.GridView1.Attributes.Add("SortDirection", "ASC");

// 绑定数据源到GridView
            this.BindGridView();
        }
    }

/// <summary>
    /// GridView排序事件
    /// </summary>
    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        // 从事件参数获取排序数据列
        string sortExpression = e.SortExpression.ToString();

// 假定为排序方向为“顺序”
        string sortDirection = "ASC";

// “ASC”与事件参数获取到的排序方向进行比较,进行GridView排序方向参数的修改
        if (sortExpression == this.GridView1.Attributes["SortExpression"])
        {
            //获得下一次的排序状态
            sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
        }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjzpgs.html