后台代码:
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;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
public void Bind()
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("abc.mdb");
string sql = "select * from grade";
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "grade");
DataView view = ds.Tables["grade"].DefaultView;
string sort=(string)ViewState["排序字段"]+" "+(string)ViewState["排序方式"];
view.Sort = sort;
GridView1.DataSource = view;
GridView1.DataBind();
conn.Close();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["排序字段"] = "语文";
ViewState["排序方式"] = "DESC";
Bind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string spage = e.SortExpression;
if (ViewState["排序字段"].ToString() == spage)
{
if (ViewState["排序方式"].ToString() == "DESC")
ViewState["排序方式"] = "ASC";
else
ViewState["排序方式"] = "DESC";
}
else
ViewState["排序字段"] = e.SortExpression;
Bind();
}
}
前台代码:
<%@ 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 id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
OnSorting="GridView1_Sorting">
<Columns>
<asp:BoundField DataField="学号" HeaderText="学号" ReadOnly="True" SortExpression="学号" />
<asp:BoundField DataField="姓名" HeaderText="姓名" SortExpression="姓名" />
<asp:BoundField DataField="性别" HeaderText="性别" SortExpression="性别" />
<asp:BoundField DataField="语文" HeaderText="语文" SortExpression="语文" />
<asp:BoundField DataField="数学" HeaderText="数学" SortExpression="数学" />
<asp:BoundField DataField="英语" HeaderText="英语" SortExpression="英语" />
<asp:BoundField DataField="综合" HeaderText="综合" SortExpression="综合" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
原文地址:http://hi.baidu.com/lsm%B5%D8%C5%CC/blog/item/51df8c08d34235226b60fb8e.html