欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net GridView排序简单实现

程序员文章站 2024-03-09 10:47:17
前台: 代码 复制代码 代码如下: <%@ page language="c#" autoeventwireup="true" codefile="gridviews...
前台:
代码
复制代码 代码如下:

<%@ page language="c#" autoeventwireup="true" codefile="gridviewsort.aspx.cs" inherits="gridviewsort" %>
<!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>gridview排序简单实现</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:gridview id="gdvsort" runat="server" onsorting="gdvsort_sorting">
</asp:gridview>
</div>
</form>
</body>
</html>

后台:

代码
复制代码 代码如下:

using system;
using system.data;
using system.configuration;
using system.collections;
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 gridviewsort : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
viewstate["sortorder"] = "pid";
viewstate["orderdire"] = "desc";
bind();
}
}
private void bind()
{
gdvsort.allowsorting = true;
dataview dv = getdt().defaultview;
dv.sort = (string)viewstate["sortorder"] + " " + (string)viewstate["orderdire"];
gdvsort.datasource = dv;
gdvsort.databind();
}
/// <summary>
/// 连数据库麻烦,直接构造一个datatable
/// </summary>
/// <returns></returns>
private datatable getdt()
{
datatable dt = new datatable();
dt.columns.add("pid", typeof(system.int32));
dt.columns.add("username", typeof(system.string));
for (int i = 0; i < 10; i++)
{
datarow dr = dt.newrow();
dr["pid"] = i;
dr["username"] = "姓名" + i;
dt.rows.add(dr);
}
return dt;
}
protected void gdvsort_sorting(object sender, gridviewsorteventargs e)
{
string spage = e.sortexpression;
if (viewstate["sortorder"].tostring() == spage)
{
if (viewstate["orderdire"].tostring() == "desc")
{
viewstate["orderdire"] = "asc";
}
else
{
viewstate["orderdire"] = "desc";
}
}
else
viewstate["sortorder"] = e.sortexpression;
bind();
}
}