GridView 分页 排序
HTML部分示例代码
----------------
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server"
AllowPaging="True" AllowSorting="True" PageSize="2" AutoGenerateColumns="False" OnPageIndexChanging="GridView1_PageIndexChanging" OnSorting="GridView1_Sorting">
<Columns>
<asp:BoundField DataField="TestID" HeaderText="TestID" SortExpression="TestID" />
<asp:BoundField DataField="TestUser" HeaderText="TestUser" SortExpression="TestUser" />
<asp:BoundField DataField="TestTime" HeaderText="TestTime" SortExpression="TestTime" />
</Columns>
</asp:GridView>
</form>
</body>
cs部分示例代码
--------------
public partial class gv : System.Web.UI.Page
{
#region Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GridView1.Attributes.Add("SortExpression", "TestID");
this.GridView1.Attributes.Add("SortDirection", "ASC");
//绑定GridView
fn_DataBind();
}
}
#endregion
#region 得到绑定GridView的DataTable
private DataTable fn_getDataTable()
{
string strSql = " SELECT TestID, TestUser, TestTime FROM Test ";
DBClass db = new DBClass();
DataSet ds = db.RunSelectGetDataSet(strSql);
return ds.Tables[0];
}
#endregion
#region 分页
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.GridView1.PageIndex = e.NewPageIndex;
fn_DataBind();
}
#endregion
#region 排序
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
if (e.SortExpression != "")
{
if (GridView1.PageCount > 0)
{
//设定排序方向
string SortDirection = "ASC";
SortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == SortDirection ? "DESC" : "ASC");
this.GridView1.Attributes["SortExpression"] = e.SortExpression;
this.GridView1.Attributes["SortDirection"] = SortDirection;
//重新绑定数据
fn_DataBind();
}
}
}
#endregion
#region 绑定GridView
private void fn_DataBind()
{
DataTable dt = fn_getDataTable();
string SortDirection = this.GridView1.Attributes["SortDirection"].ToString();
string SortExpression = this.GridView1.Attributes["SortExpression"].ToString();
dt.DefaultView.Sort = string.Format("{0} {1}", SortExpression, SortDirection);
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
#endregion
}
posted on 2007-08-09 11:18 freeliver54 阅读(1395) 评论(0) 编辑 收藏 举报