GridView正反双向排序

来源:互联网 发布:威少数据 编辑:程序博客网 时间:2024/04/29 23:06

后台代码:

using System;
using System.Data;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace WebApplication1
{
    public partial class sort : System.Web.UI.Page
    {
        SqlConnection sqlCon;
        string strCon = "Data Source=.;Database=pubs;uid=sa;pwd=";
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                ViewState["SortOrder"] = "au_id";
                ViewState["SortDire"] = "ASC";
                bind();
            }
        }
        public void bind()
        {
            string strSql = "select top 5 * from authors";
            sqlCon = new SqlConnection(strCon);
            SqlDataAdapter sqlDap = new SqlDataAdapter(strSql, sqlCon);
            DataSet dataSet = new DataSet();
            sqlCon.Open();
            sqlDap.Fill(dataSet, "authors");
            DataView view = dataSet.Tables["authors"].DefaultView;
            string sort = (string)ViewState["SortOrder"] + " " + ViewState["SortDire"];
            view.Sort = sort;
            GridView1.DataSource = view;       
            GridView1.DataBind();
            sqlCon.Close();
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            if (ViewState["SortOrder"].ToString() == sPage)
            {
                if (ViewState["SortDire"].ToString() == "DESC")
                    ViewState["SortDire"] = "ASC";
                else
                {
                    ViewState["SortDire"] = "DESC";
                }
            }
            else
            {
                ViewState["SortOrder"] = e.SortExpression;
            }
            bind();
        }
    }
}

前台主要代码:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            CellPadding="4" ForeColor="#333333" GridLines="None"
            onsorting="GridView1_Sorting" AllowSorting="True">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <Columns>
                <asp:BoundField DataField="au_id" HeaderText="身份证号码" SortExpression="au_id" />
                <asp:BoundField DataField="au_fname" HeaderText="姓名" SortExpression="au_fname" />
                <asp:BoundField DataField="address" HeaderText="地址" SortExpression="address" />
            </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>

 

note:AllowSorting一定要设置为true;还要设置SortExpression。

原创粉丝点击