ASP.NET用于数据源控件分页的用户控件

最近在做一个ACCESS的小项目,用到一处分页,以前我都是用自定义控件,这次我改用了用户控件,重新写了代码。

实现效果如下:

ASP.NET用于数据源控件分页的用户控件

1、分页控件制作

分页控件HTML代码Pagination.ascx:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Pagination.ascx.cs" Inherits="HuiYingWeb.Controls.Pagination" %> <table cellpadding="2" cellspacing="0" width="100%" > <tr> <td align="left"> <asp:LinkButton ID="lbnFirstPage" runat="server" OnClick="lbnFirstPage_Click">[首页]</asp:LinkButton> <asp:LinkButton ID="lbnPrePage" runat="server" OnClick="lbnPrePage_Click">[上一页]</asp:LinkButton> <asp:LinkButton ID="lbnPageNext" runat="server" OnClick="lbnPageNext_Click">[下一页]</asp:LinkButton> <asp:LinkButton ID="lbnLastPage" runat="server" OnClick="lbnLastPage_Click">[尾页]</asp:LinkButton> <asp:Label ID="Label1" runat="server"></asp:Label> </td> <td align="right"> 每页显示<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> <asp:ListItem Value="20" Selected="True">20条</asp:ListItem> <asp:ListItem Value="30">30条</asp:ListItem> <asp:ListItem Value="40">40条</asp:ListItem> </asp:DropDownList> 转到<asp:TextBox ID="TextBox1" runat="server" Width="25px"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Go" BorderWidth="1px" /> </td> </tr> </table>

分页控件程序逻辑代码Pagination.ascx.cs:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; //需要导入的命名空间 using System.Text; using System.Data; using System.Data.OleDb; using System.Configuration; using Maticsoft.DBUtility; namespace HuiYingWeb.Controls { public partial class Pagination : System.Web.UI.UserControl { private object controlName=null; //要分页的控件名 private string tableName=string.Empty; //表名 private string primaryKey = string.Empty; //主键名 private string where = string.Empty; //SQL条件 private string orderBy = string.Empty; //排序条件 private string descOrAsc = "Desc"; //降序或升序 protected string connStr = PubConstant.ConnectionString; //获得数据库连接字符串 // ConfigurationManager.AppSettings["ConnectionString"];// ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { //获得每页显示条数 PageCount = int.Parse(DropDownList1.SelectedItem.Value); if (Page.IsPostBack == false) { PageIndex = 1; //设置默认值 } //绑定数据 dataBind(PageIndex, PageCount, where); } /// <summary> /// 绑定数据显示到页面 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageCount"></param> /// <param name="where"></param> private void dataBind(int pageIndex, int pageCount,string where) { string strWhere = string.Empty; if (where.Length == 0) strWhere = " 1=1 "; else strWhere = " " + where; string strSql = "select * from " + TableName + " where " + where + " Order By " + orderBy +" "+descOrAsc+",FID DESC"; //获得数据 DataTable dt = getDataTable(getSQL(strSql, PageIndex, PageCount, OrderBy)); //判断传入的是哪种数据源控件 if (controlName is System.Web.UI.WebControls.GridView) { (controlName as GridView).DataSource = dt; (controlName as GridView).DataBind(); } else if (controlName is System.Web.UI.WebControls.DataList) { (controlName as DataList).DataSource = dt; (controlName as DataList).DataBind(); } //按钮及提示信息的显示 ButtonState(pageCount); } /// <summary> /// 按钮及提示信息的显示 /// </summary> /// <param name="pageCount">每页显示的条数</param> private void ButtonState(int pageCount) { lbnPrePage.Enabled = (PageIndex > 1) ? true : false; lbnFirstPage.Enabled = (PageIndex > 1) ? true : false; lbnPageNext.Enabled = (PageIndex == LastPage) ? false : true; lbnLastPage.Enabled = (PageIndex == LastPage) ? false : true; string str = string.Empty; //如果一页就全显示了 if (PageIndex == 1) { //如果每页显示的记录数大于总记录数,则记录结束处以总记录数为准 if (PageIndex == LastPage && pageCount>AllCount) str = PageIndex.ToString() + "-" + AllCount.ToString(); else str = PageIndex.ToString() + "-" + (PageIndex * PageCount).ToString(); } else { //记录开始处 int recordStart = (PageIndex - 1) * PageCount + 1; //记录结束处 int recordEnd = 1; //如果是最后一页 if (PageIndex == LastPage) recordEnd = AllCount; else recordEnd = (PageIndex * PageCount); str = recordStart.ToString() + "-" + recordEnd.ToString(); } Label1.Text = "记录" + str + "条/共" + AllCount + "条 第" + PageIndex + "页/共" + LastPage + "页"; if (AllCount == 0) { lbnPageNext.Enabled = false; lbnLastPage.Enabled =false; Label1.Text = "记录0-0条/共0条 第0页/共0页"; } } /// <summary> /// 选择每页显示的记录数 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { PageIndex = 1; PageCount = int.Parse(DropDownList1.SelectedItem.Value); dataBind(PageIndex, PageCount,this.where); } /// <summary> /// 首页 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void lbnFirstPage_Click(object sender, EventArgs e) { PageIndex = 1; PageCount = int.Parse(DropDownList1.SelectedItem.Value); dataBind(PageIndex, PageCount,this.where); } // 下一页 protected void lbnPageNext_Click(object sender, EventArgs e) { PageIndex++; PageCount = int.Parse(DropDownList1.SelectedItem.Value); dataBind(PageIndex, PageCount,this.where); } // 前一页 protected void lbnPrePage_Click(object sender, EventArgs e) { PageIndex--; PageCount = int.Parse(DropDownList1.SelectedItem.Value); dataBind(PageIndex, PageCount,this.where); } // 末页 protected void lbnLastPage_Click(object sender, EventArgs e) { PageIndex = LastPage; PageCount = int.Parse(DropDownList1.SelectedItem.Value); dataBind(PageIndex, PageCount,this.where); } // 转到指定页 protected void Button1_Click(object sender, EventArgs e) { try { PageIndex = int.Parse(TextBox1.Text); if (PageIndex <= 0) PageIndex = 1; else if (PageIndex >= LastPage) PageIndex = LastPage; } catch { PageIndex = 1; } dataBind(PageIndex, PageCount,this.where); TextBox1.Text = ""; } /// <summary> /// 传入查询SQL语句,生成分页的SQL语句 /// </summary> /// <param name="strSQL">查询SQL语句</param> /// <param name="pageIndex">当前页</param> /// <param name="pageCount">每页显示记录数</param> /// <param name="orderField">排序字段 (如果有多个字段,最后一个字段不能带Desc或Asc)</param> /// <returns></returns> protected string getSQL(string strSQL, int pageIndex, int pageCount, string orderField) { GetAllCount(strSQL); //把传入的SQL语句的查询结果起个别名tempTable if (strSQL != "") strSQL = " ( " + strSQL + " ) tempTable"; else return ""; //已阅读(跳过)的记录数 int count = pageIndex * pageCount; if (pageIndex == LastPage) { count = AllCount; pageCount = (AllCount % pageCount == 0) ? pageCount : AllCount % pageCount; } string strSql = ""; //方法一: strSql += "select * from( "; strSql += "select top " + pageCount.ToString() + " * from ( "; //strSql += "select top " + count.ToString() + " * from " + strSQL + " order by " + primaryKey + ") as Ta order by " + primaryKey + " desc)as Tb order by " + orderField; strSql += "select top " + count.ToString() + " * from " + strSQL + " order by " + orderField + " "+descOrAsc+",FID DESC) as Ta order by " + orderField + ",FID DESC)as Tb order by " + orderField + " "+descOrAsc+",FID DESC"; //方法二 需要完善: //if (pageIndex == 1) //{ // strSql += "select top " + pageCount.ToString() + " * from " + tableName + " Order by " + orderField; //} //else //{ // // // strSql += "select top " + pageCount.ToString() + " * from " + TableName + " where ( " + PrimaryKey + ">"; // strSql += "(select MAX(" + PrimaryKey + ") from (select top " + count + " " + primaryKey + " from " + TableName +" where "+Where+ " Order by " + primaryKey + " ) as T)) Order by " + orderField; //} return strSql; } /// <summary> /// 根据传入的SQL字符串获得记录数的方法 /// </summary> /// <param name="strSQL"></param> /// <returns></returns> public int GetAllCount(string strSQL) { //把传入的SQL语句的查询结果起个别名tempTable if (strSQL != "") strSQL = "select count(*) from (" + strSQL + ") tempTable"; else return -1; int allCount = int.Parse(getDataTable(strSQL).Rows[0][0].ToString()); ViewState["AllCount"] = allCount; return allCount; } /// <summary> /// 根据查询语句获得一个DataTable对象的基本方法 /// </summary> /// <param name="strSql"></param> /// <returns></returns> public DataTable getDataTable(String strSql) { OleDbConnection conn = new OleDbConnection(connStr); OleDbCommand cmm = new OleDbCommand(strSql, conn); OleDbDataAdapter dap = new OleDbDataAdapter(cmm); DataSet ds = new DataSet(); dap.Fill(ds); return ds.Tables[0]; } /// <summary> /// 总记录数 /// </summary> public int AllCount { get { return (int)ViewState["AllCount"]; } } /// <summary> /// 最后一页 /// </summary> public int LastPage { get { int lastPage = 1; if (AllCount % PageCount == 0) lastPage = AllCount / PageCount; else lastPage = AllCount / PageCount + 1; return lastPage; } } /// <summary> /// 当前页 /// </summary> public int PageIndex { get { return int.Parse(ViewState["PageIndex"].ToString()); } set { ViewState["PageIndex"] = value; } } /// <summary> /// 每页显示的条数 /// </summary> public int PageCount { get { return (int)ViewState["PageCount"]; } set { ViewState["PageCount"] = value; } } //---------------------以下为分页控件增加的属性(2011年1月)-----------------------// /// <summary> /// 获得或设置要分页的控件 /// </summary> public object ControlName { get { return controlName; } set { controlName = value; } } /// <summary> /// 表名 /// </summary> public string TableName { get { return tableName; } set { tableName = value; } } /// <summary> /// 表的主键名 /// </summary> public string PrimaryKey { get { return primaryKey; } set { primaryKey = value; } } /// <summary> /// SQL条件 /// </summary> public string Where { get { string strWhere = ""; if (where.Length == 0) strWhere = " 1=1 "; else strWhere = " " + where; return strWhere; } set { where = value; } } /// <summary> /// SQL排序字段 /// </summary> public string OrderBy { get { return orderBy; } set { orderBy = value; } } /// <summary> /// 降序或升序 /// </summary> public string DescOrAsc { get { return descOrAsc; } set { descOrAsc = value; } } } }

2、分页控件的使用

前台代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="HuiYingWeb.Content.WebForm2" %> <%@ Register Src="../Controls/Pagination.ascx" TagName="Pagination" TagPrefix="uc1" %> <!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> <link href="../Style/Style.css" mce_href="Style/Style.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <asp:DataList ID="DataList1" runat="server" CellPadding="2" Width="100%"> <ItemTemplate> <table border="0" cellpadding="0" cellspacing="0" style="width: 100%"> <tr> <td align="left"> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "ShowContent.aspx?Id="+Eval("FID") %>' Text='<%# Eval("FTitle").ToString() %>'></asp:HyperLink> </td> <td align="right"> <asp:Label ID="Label1" runat="server" Text='<%# Eval("FWriteDate").ToString() %>'></asp:Label> </td> </tr> </table> </ItemTemplate> </asp:DataList><br /> <uc1:Pagination ID="Pagination1" runat="server" /> </div> </form> </body> </html>

后台代码:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace HuiYingWeb.Content { public partial class WebForm2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //指定分页要的控件,数据源表名,主键名 Pagination1.ControlName = DataList1; //要分页的控件名 Pagination1.TableName = "TContent"; //数据源主表名 Pagination1.PrimaryKey = "FID"; //数据源主键 Pagination1.Where = "FID>50 And FSectionID=5"; //条件 Pagination1.OrderBy = "FWriteDate"; //排序字段 } } }