ASP.NET技巧:access下的分页方案

具体不多说了,只贴出相关源码~

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Web;

/**//// <summary>
/// 名称:access下的分页方案(仿sql存储过程)
/// 作者:cncxz(虫虫)
/// blog:http://cncxz.cnblogs.com
/// </summary>
public class AdoPager
{
    protected string m_ConnString;
    protected OleDbConnection m_Conn;

public AdoPager()
    {
        CreateConn(string.Empty);
    }
    public AdoPager(string dbPath)
    {
        CreateConn(dbPath);
    }

private void CreateConn(string dbPath)
    {
        if (string.IsNullOrEmpty(dbPath))
        {
            string str = System.Configuration.ConfigurationManager.AppSettings["dbPath"] as string;
            if (string.IsNullOrEmpty(str))
                str = "~/App_Data/db.mdb";
            m_ConnString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data source={0}", HttpContext.Current.Server.MapPath(str));
        }
        else
            m_ConnString = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data source={0}", dbPath);

m_Conn = new OleDbConnection(m_ConnString);
    }
    /**//// <summary>
    /// 打开连接
    /// </summary>
    public void ConnOpen()
    {
        if (m_Conn.State != ConnectionState.Open)
            m_Conn.Open();
    }
    /**//// <summary>
    /// 关闭连接
    /// </summary>
    public void ConnClose()
    {
        if (m_Conn.State != ConnectionState.Closed)
            m_Conn.Close();
    }

private string recordID(string query, int passCount)
    {
        OleDbCommand cmd = new OleDbCommand(query, m_Conn);
        string result = string.Empty;
        using (IDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                if (passCount < 1)
                {
                    result += "," + dr.GetInt32(0);
                }
                passCount--;
            }
        }
        return result.Substring(1);
    }

/**//// <summary>
    /// 获取当前页应该显示的记录,注意:查询中必须包含名为ID的自动编号列,若不符合你的要求,就修改一下源码吧 :)
    /// </summary>
    /// <param name="pageIndex">当前页码</param>
    /// <param name="pageSize">分页容量</param>
    /// <param name="showString">显示的字段</param>
    /// <param name="queryString">查询字符串,支持联合查询</param>
    /// <param name="whereString">查询条件,若有条件限制则必须以where 开头</param>
    /// <param name="orderString">排序规则</param>
    /// <param name="pageCount">传出参数:总页数统计</param>
    /// <param name="recordCount">传出参数:总记录统计</param>
    /// <returns>装载记录的DataTable</returns>
    public DataTable ExecutePager(int pageIndex, int pageSize, string showString, string queryString, string whereString, string orderString, out int pageCount, out int recordCount)
    {
        if (pageIndex < 1) pageIndex = 1;
        if (pageSize < 1) pageSize = 10;
        if (string.IsNullOrEmpty(showString)) showString = "*";
        if (string.IsNullOrEmpty(orderString)) orderString = "ID desc";
        ConnOpen();
        string myVw = string.Format(" ( {0} ) tempVw ", queryString);
        OleDbCommand cmdCount = new OleDbCommand(string.Format(" select count(0) as recordCount from {0} {1}", myVw, whereString), m_Conn);

recordCount = Convert.ToInt32(cmdCount.ExecuteScalar());

if ((recordCount % pageSize) > 0)
            pageCount = recordCount / pageSize + 1;
        else
            pageCount = recordCount / pageSize;
        OleDbCommand cmdRecord;
        if (pageIndex == 1)//第一页
        {
            cmdRecord = new OleDbCommand(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageSize, showString, myVw, whereString, orderString), m_Conn);
        }
        else if (pageIndex > pageCount)//超出总页数
        {
            cmdRecord = new OleDbCommand(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageSize, showString, myVw, "where 1=2", orderString), m_Conn);
        }
        else
        {
            int pageLowerBound = pageSize * pageIndex;
            int pageUpperBound = pageLowerBound - pageSize;
            string recordIDs = recordID(string.Format("select top {0} {1} from {2} {3} order by {4} ", pageLowerBound, "ID", myVw, whereString, orderString), pageUpperBound);
            cmdRecord = new OleDbCommand(string.Format("select {0} from {1} where id in ({2}) order by {3} ", showString, myVw, recordIDs, orderString), m_Conn);

}
        OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmdRecord);
        DataTable dt=new DataTable();
        dataAdapter.Fill(dt);
        ConnClose();
        return dt;
    }
}

还有调用示例:html代码

<%@ 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>
        <br />
          转到第<asp:TextBox ID="txtPageSize" runat="server" Width="29px">1</asp:TextBox>页<asp:Button ID="btnJump" runat="server" Text="Go" OnClick="btnJump_Click" /><br />
        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" Width="90%">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2461BF" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        </asp:GridView>

</div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

示例的codebehind代码

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.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    private AdoPager mm_Pager;
    protected AdoPager m_Pager
    {
        get{
            if (mm_Pager == null)
                mm_Pager = new AdoPager();
            return mm_Pager;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
            LoadData();
    }
    private int pageIndex = 1;
    private int pageSize = 20;
    private int pageCount = -1;
    private int recordCount = -1;

private void LoadData()
    {
        string strQuery = "select a.*,b.KindText from tableTest a left join tableKind b on a.KindCode=b.KindCode ";
        string strShow = "ID,Subject,KindCode,KindText";

DataTable dt = m_Pager.ExecutePager(pageIndex, pageSize, strShow, strQuery, "", "ID desc", out pageCount, out recordCount);
        GridView1.DataSource = dt;
        GridView1.DataBind();
        Label1.Text = string.Format("共{0}条记录,每页{1}条,页次{2}/{3}",recordCount,pageSize,pageIndex,pageCount);
    }

protected void btnJump_Click(object sender, EventArgs e)
    {
        int.TryParse(txtPageSize.Text, out pageIndex);
        LoadData();
    }
}

(0)

相关推荐

  • Asp.net中使用PageDataSource分页实现代码

    复制代码 代码如下: 注:封装数据绑定控件(如 System.Web.UI.WebControls.DataGrid.System.Web.UI.WebControls.GridView.System.Web.UI.WebControls.DetailsView    //     和 System.Web.UI.WebControls.FormView)的与分页相关的属性,以允许该控件执行分页操作.无法继承此类.DataListpublic DataTable GetDataSet(strin

  • asp.net中使用repeater和PageDataSource搭配实现分页代码

    复制代码 代码如下: PagedDataSource objPage = new PagedDataSource(); DataView dv = bllBook.GetListByState("", true);            //设置数据源            objPage.DataSource =dv ; //允许分页            objPage.AllowPaging = true; //设置每页显示的项数            objPage.PageS

  • asp.net利用存储过程和div+css实现分页(类似于博客园首页分页)

    首先声明以下几点: 1.也许讲解有点初级,希望高手不要"喷"我,因为我知道并不是每一个人都是高手,我也怕高手们说我装13,小生不才: 2.如有什么不对的地方,还希望大家指出,一定虚心学习: 3.本文属于作者原创,尊重他人劳动成果,转载请注明作者,谢谢. 下面开讲: 首先说下思路,写一个存储过程,我也找了一个存储过程,不过不是我写的,出处:http://www.cnblogs.com/zhongweiv/archive/2011/10/31/JqueryPagination.html 这

  • .NET 纯分页代码实例

    前台 复制代码 代码如下: <div class="mydiv"   style="width:100%;height:180px;background-color:#f0f7ff">             <div style="margin-left:10px;">                   <div style="background-color:#DAEBFF"><

  • asp.net Repeater分页实例(PageDataSource的使用)

    Asp.net提供了三个功能强大的列表控件:DataGrid.DataList和Repeater控件,但其中只有DataGrid控件提供分页功能.相对DataGrid,DataList和Repeater控件具有更高的样式自定义性,所以很多时候我们喜欢使用DataList或Repeater控件来显示数据. 实现DataList或Repeater控件的分页显示有几种方法: 1.写一个方法或存储过程,根据传入的页数返回需要显示的数据表(DataTable) 2.使用PagedDataSource类(位

  • asp.net 使用ObjectDataSource控件在ASP.NET中实现Ajax真分页

    ListView控件本身并没有分页功能,不过借助于ASP.NET中新增加的DataPager控件,我们可以非常方便地对ListView中的数据设置分页,这几乎不需要开发人员写一行代码,将ListView控件放到页面上,设置好布局和DataSource,然后再添加一个DataPager控件,将它的PagedControlID属性设置成ListView的ID,PageSize中设置每页要显示的数据条数,然后在Fields中设置好分页的样式(当然你完全可以不用去管样式,ASP.NET会根据内置的样式来

  • 一个简答的Access下的分页asp.net代码

    复制代码 代码如下: public void listArticle() { CmsArticle arObj = new CmsArticle(); DataSet ds = arObj.listArticle(); if (ds != null) { PagedDataSource pds = new PagedDataSource(); pds.DataSource = ds.Tables[0].DefaultView; pds.AllowPaging = true; pds.PageSi

  • ASP.NET技巧:access下的分页方案

    具体不多说了,只贴出相关源码~ using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Data.OleDb;using System.Web; /**//// <summary>/// 名称:access下的分页方案(仿sql存储过程)/// 作者:cncxz(虫虫)/// blog:http://cncxz.cnblogs.com/// </summa

  • asp.net实现access数据库分页的方法

    asp.net操作access数据库是常见的数据库操作应用,本文就来实例讲解一下asp.net实现access数据库分页的方法.希望对大家的asp.net程序设计能有所帮助. 具体实例代码如下: <divclass="page"id="ctrlRecordPage"> 总<asp:LabelID="Zpage"runat="server"Text="1"></asp:Label

  • ASP.Net MVC+Data Table实现分页+排序功能的方法

    本文实例讲述了ASP.Net MVC+Data Table实现分页+排序功能的方法.分享给大家供大家参考,具体如下: 实现思路: 使用datatable内置的分页,排序 使用attribute+反射来控制需要排序和显示的字段以及顺序 分离排序和显示逻辑 若要添加搜索逻辑只需要传递搜索的字段到后端即可(js初始化时把"searching": false拿掉). View : @using BCMS.BusinessLogic @using BCMS.BusinessLogic.Model

  • 深入浅析ASP在线压缩access数据库的方法

    ASP在线压缩ACCESS数据库原理很简单:利用JRO.JetEngine的压缩功能建立一个新的数据库文件,然后把原来的删掉.替换!既然这样,压缩程序只需几行就ok了! 把下面的代码保存为**.asp,数据库文件(db.md)放在相同目录下,执行asp搞定! <% oldDB = server.mappath("db.mdb") '更改数据库地址 newDB = server.mappath("db_new.mdb") '生成临时文件 Set FSO = Se

  • ASP.NET实现级联下拉框效果实例讲解

    用ASP.NET控件实现部门和员工的联动,参考过程如下 效果图: Default.aspx代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/199

  • Asp.Net程序目录下文件夹或文件操作导致Session失效的解决方案

    1.配置web.config <system.web> <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="

  • 水晶报表asp.net的webform下基本用法实例

    本文实例讲述了水晶报表asp.net的webform下基本用法.分享给大家供大家参考. 具体实现方法如下: 复制代码 代码如下: protected void Page_Init(object sender, EventArgs e) {      ConfigureCrystalReport();  } protected void Page_Unload(object sender, EventArgs e)  {          if (rptDocument == null)     

  • ASP+JS三级联动下拉菜单[调用数据库数据]

    网上三级菜单多是多但是代码都比较烦,我这个应该说还是比较直观的:'肯定先要连接数据库了,不用说了 '数据库结构 '类别1表名称:a  字段:ID,Name  说明:ID为主键是类别1的ID值,Name为类别1的名称 '类别2表名称:aa  字段:ID,aID,Name  说明:ID为主键是类别2的ID值,aID为所属类别1的ID值,Name为类别2的名称 '类别3表名称:aaa  字段:ID,aID,aaID,Name  说明:ID为主键是类别3的ID值,aID为所属类别1的ID值,aaID为所

随机推荐