效果如图:

首先允许排序:AllowSorting="True";开启gridview的排序事件onsorting="GridView1_Sorting",也可以双击sorting事件;其次是设置nrowdatabound="GridView1_RowDataBound",也可以双击GridView1_RowDataBound

关联排序表达式SortExpression="字段名称"

代码明细:

前台代码:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" Width="800px"
AllowSorting="True"
onrowdatabound="GridView1_RowDataBound" onsorting="GridView1_Sorting"
PageSize="15">
<PagerSettings Mode="NumericFirstLast"/>
<RowStyle BackColor="#EFF3FB"/>
<Columns>
<asp:BoundField DataField="CourseResID" HeaderText="课程ID"/>
<asp:BoundField DataField="CourseName" HeaderText="课程名" SortExpression="CourseName">
<ItemStyle Width="100px"/>
</asp:BoundField>
<asp:BoundField DataField="upTime" HeaderText="更新时间"
DataFormatString="{0:yyyy-MM-dd}" SortExpression="upTime">
<ItemStyle Width="160px" HorizontalAlign="Right"/>
</asp:BoundField>
<asp:BoundField DataField="UserName" HeaderText="用户名" SortExpression="UserName">
<ItemStyle Width="80px" ForeColor="#33CC33"/>
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"/>
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Right"/>
<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>

数据读取

///<summary>
/// 获取绑定数据
///</summary>
///<param name="orderFields">排序信息</param>
///<returns>返回表</returns>
public DataTable GetContents(string orderFields)
{
string cmdTxt ="Select top 30 * From CourseRes";
//判断排序字段是否为空,如果不为空则将排序信息加在Sql语句后面
if (!string.IsNullOrEmpty(orderFields))
{
cmdTxt +=" Order By "+ orderFields;
}
SqlConnection conn =new SqlConnection(@"Data Source=HAPPY-WITBANK;Initial Catalog=le2011;Persist Security Info=True;User ID=sa;Password=happy");
SqlCommand comm =new SqlCommand(cmdTxt, conn);
SqlDataAdapter adap =new SqlDataAdapter(comm);
DataTable dt =new DataTable();
adap.Fill(dt);

return dt;
}

排序信息代码,可以通用;注,要用时只需将上面的绑定Sql数据修改即可

publicpartialclass 自定义分页 : System.Web.UI.Page
{
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataLoad();
}
}
///<summary>
/// 数据加载
///</summary>
privatevoid DataLoad()
{
string sortedField ="";
//获取排序字段的信息
if (ViewState["SortedField"] !=null)
{
//如果存在排序信息,则将排序信息转换为字典存储
Dictionary<string, string> sorted = (Dictionary<string, string>)ViewState["SortedField"];
//便利取值
foreach (KeyValuePair<string, string> kvp in sorted)
{
//key排序字段,value排序信息
sortedField = kvp.Key +""+ kvp.Value;
}
}

//数据绑定
this.GridView1.DataSource = GetContents(sortedField);
this.GridView1.DataBind();
}

protectedvoid GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
#region//加排序的头方法
//判断是否是表头
if (e.Row.RowType == DataControlRowType.Header)
{
//判断是否进行排序
if (ViewState["SortedField"] !=null)
{
//恢复排序信息
Dictionary<string, string> order = (Dictionary<string, string>)ViewState["SortedField"];
//循环表头的单元格,判断是否有需要排序的单元格
for (int i =0; i < e.Row.Cells.Count; i++)
{
if (e.Row.Cells[i].Controls.Count >0)
{
//是否是排序字段信息
LinkButton lb = e.Row.Cells[i].Controls[0] as LinkButton;
if (lb !=null)
{
//反序和降序
if (order.ContainsKey(lb.CommandArgument))
{
Literal li =new Literal();
if (order[lb.CommandArgument] =="ASC")
{
li.Text ="▲";
}
else
{
li.Text ="▼";
}
//
e.Row.Cells[i].Controls.Add(li);
}
}
}
}
}
}
#endregion 完成排序

}

protectedvoid GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//
Dictionary<string, string> sorted =new Dictionary<string, string>();
//从ViewState读取上一次的排序信息。
if (ViewState["SortedField"] ==null)
{
//如果没有排序信息,则将当前点击的对象(即点击的排序字段)和排序信息添加到字典中
sorted.Add(e.SortExpression, "ASC");
//将排序信息放在字典中保存
ViewState["SortedField"] = sorted;
}
else
{
//判断是否点击相同的排序,如果是相同的排序,
//就是用反序
//如果不是想通的排序,那就新的派讯,是用升序
sorted = (Dictionary<string, string>)ViewState["SortedField"];
if (sorted.ContainsKey(e.SortExpression))
{
if (sorted[e.SortExpression] =="ASC")
{
sorted[e.SortExpression] ="DESC";
}
else
{
sorted[e.SortExpression] ="ASC";
}
}
else
{
sorted.Clear();
sorted.Add(e.SortExpression, "ASC");
ViewState["SortedField"] = sorted;
}
}

//重新加载数据
DataLoad();

}
}

gridview自定义排序的更多相关文章

  1. Java集合框架实现自定义排序

    Java集合框架针对不同的数据结构提供了多种排序的方法,虽然很多时候我们可以自己实现排序,比如数组等,但是灵活的使用JDK提供的排序方法,可以提高开发效率,而且通常JDK的实现要比自己造的轮子性能更优 ...

  2. DataTable自定义排序

    使用JQ DataTable 的时候,希望某列数据可以进行自定义排序,操作如下:(以中文排序和百分比排序为例) 1:定义排序类型: //百分率排序 jQuery.fn.dataTableExt.oSo ...

  3. 干货之UICollectionViewFlowLayout自定义排序和拖拽手势

    使用UICollectionView,需要使用UICollectionViewLayout控制UICollectionViewCell布局,虽然UICollectionViewLayout提供了高度自 ...

  4. DataGridView 绑定List集合后实现自定义排序

    这里只贴主要代码,dataList是已添加数据的全局变量,绑定数据源 datagridview1.DataSource = dataList,以下是核心代码. 实现点击列表头实现自定义排序 priva ...

  5. 【转】c++中Vector等STL容器的自定义排序

    如果要自己定义STL容器的元素类最好满足STL容器对元素的要求    必须要求:     1.Copy构造函数     2.赋值=操作符     3.能够销毁对象的析构函数    另外:     1. ...

  6. mysql如何用order by 自定义排序

    mysql如何用order by 自定义排序 id name roleId aaa bbb ccc ddd eee ,MySQL可以通过field()函数自定义排序,格式:field(value,st ...

  7. python 自定义排序函数

    自定义排序函数 Python内置的 sorted()函数可对list进行排序: >>>sorted([36, 5, 12, 9, 21]) [5, 9, 12, 21, 36] 但 ...

  8. 定制对ArrayList的sort方法的自定义排序

    java中的ArrayList需要通过collections类的sort方法来进行排序 如果想自定义排序方式则需要有类来实现Comparator接口并重写compare方法 调用sort方法时将Arr ...

  9. Qt之QHeaderView自定义排序(获取正确的QModelIndex)

    简述 前几节中分享过关于自定义排序的功能,貌似我们之前的内容已经可以很好地解决排序问题了,但是,会由此引发一些很难发现的问题...比如:获取QModelIndex索引错误. 下面,我们先来实现一个整行 ...

随机推荐

  1. IPv6地址介绍

    IPv6地址介绍 2008 年 04 月 10 日 1. 认识IPv6地址 IPv4地址是类似 A.B.C.D 的格式,它是32位,用\".\"分成四段,用10进制表示:而IPv6 ...

  2. maximum subarray problem

    In computer science, the maximum subarray problem is the task of finding the contiguous subarray wit ...

  3. 二、JavaScript语言--JS实践--商城分类导航效果

    商城类导航菜单制作(以京东为例--竖向列表横向伸缩) 可以用两种方式来实现:用CSS实现和用JS实现 方法一:用CSS实现(要点:使用hover) <!DOCTYPE html PUBLIC & ...

  4. 苹果官方制作MAC OS的启动U盘的步骤

    工具/原料 一个8G或者更大容量的U盘 MAC OS系统镜像DMG文件 方法/步骤 1.打开应用程序 - 使用工具里的磁盘工具,将U盘格式化为MAC OS扩展日志式,名称输入Mavericks,并创建 ...

  5. YCbCr 编码格式(YUV)---转自Crazy Bingo的博客

    YCbCr是DVD.摄像机.数字电视等消费类视频产品中,常用的色彩编码方案. YCbCr 有时会称为 YCC..Y'CbCr 在模拟分量视频(analog component video)中也常被称为 ...

  6. Jquery.Datatables 服务器处理(Server-side processing)

    看了看介绍 http://datatables.club/manual/server-side.html 没有经过处理的分页,先显示出来看看效果,就这样写(存储过程自己写) cshtml " ...

  7. SQL小纸条--一些方便平时参考的SQL语句--随用随查

    SQL 语句 语句 语法 AND / OR SELECT column_name(s)FROM table_nameWHERE conditionAND|OR condition ALTER TABL ...

  8. Eclipse 快捷键 转换为Netbeans 快捷键

    一直使用netbeans IDE开发,习惯了netbeans的快捷键,最近要开发个app就选择了H5. 接着使用了HBuilder (基于Eclipse开发) 总体来讲这个IDE还可以,不管是代码提示 ...

  9. python中最简单的多进程程序

    学着.. #!/usr/bin/env python # -*- coding: utf-8 -*- # Spawn a Process: Chapter 3: Process Based Paral ...

  10. [LeetCode] Remove Duplicates from Sorted List II

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numb ...