我们在很多的第三方控件中都会发现有点击列头进行排序的功能,其实,在GridView控件中也是可以实现的,下面我们就看看如何在
GridView控件中实现排序的示例。
以下为实现在GridView控件排序功能的全部代码,各位只需复制粘贴到vs中即可运行。
前台代码:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" CellPadding="3" OnSorting="GridView1_Sorting" >
<Columns >
<asp:BoundField DataField="身份证号码" HeaderText="用户ID" SortExpression="身份证号码" / >
<asp:BoundField DataField="姓名" HeaderText="用户姓名" SortExpression="姓名"/ >
<asp:BoundField DataField="员工性别" HeaderText="性别" SortExpression="员工性别"/ >
<asp:BoundField DataField="家庭住址" HeaderText="家庭住址" SortExpression="家庭住址"/ >
</Columns >
</asp:GridView >
后台代码:
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;
using System.Data.SqlClient;
public partial class Default1 : System.Web.UI.Page
{
SqlConnection sqlcon;
string strCon = "Data Source=(local);Database=测试表;Uid=sa;Pwd=";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["SortOrder"] = "身份证号码";
ViewState["OrderDire"] = "ASC";
bind();
}
}
protected void GridView1_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();
}
public void bind()
{
string sqlstr = "select * from 测试表";
sqlcon = new SqlConnection(strCon);
SqlDataAdapter myda = new SqlDataAdapter(sqlstr, sqlcon);
DataSet myds = new DataSet();
sqlcon.Open();
myda.Fill(myds, "测试表");
DataView view = myds.Tables["测试表"].DefaultView;
string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
view.Sort = sort;
GridView1.DataSource = view;
GridView1.DataBind();
sqlcon.Close();
}
}
以上内容来源于互联网,原作者已无法得知,在此感谢原作者的无私奉献。弫?N
ghV峇!k鷁藌