Asp. NET tip: The paging scheme in Access _ Practical tips

Source: Internet
Author: User

Specifically not much said, only posted the relevant source code ~

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

/**////<summary>
Name: Paging scheme under Access (imitation SQL stored procedure)
Author: cncxz (insect worm)
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>
Open connection
</summary>
public void Connopen ()
{
if (m_conn.state!= ConnectionState.Open)
M_conn.open ();
}
/**////<summary>
Close connection
</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>
Get the record that the current page should display, note: The query must contain an AutoNumber column named ID, if it does not meet your requirements, modify the source code:)
</summary>
<param name= "PageIndex" > current page number </param>
<param name= "PageSize" > Paging capacity </param>
<param name= "showstring" > Displayed fields </param>
<param name= "QueryString" > Query string, support federated query </param>
<param name= "wherestring" > Query conditions, which must begin with a where if conditional restrictions </param>
<param name= "orderstring" > Sorting Rules </param>
<param name= "PageCount" > Outgoing Parameters: Total page Count </param>
<param name= "RecordCount" > Outgoing parameters: Total record statistics </param>
<returns> Loading Records of datatable</returns>
Public DataTable executepager (int pageIndex, int pageSize, String showstring, String querystring, String wherestring, Stri Ng 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)//First page
{
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)//exceeding total number of pages
{
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), Pageupperbo und);
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;
}
}

And the call example: HTML code

<%@ 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">

http://www.w3.org/1999/xhtml">
<title> Pagination Demo </title>

<body>
<form id= "Form1" runat= "Server" >
<div>
<br/>
Go to <asp:textbox id= "txtpagesize" runat= "Server" width= "29px" >1</asp:TextBox> page <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"/>
<alternatingrowstyle backcolor= "White"/>
</asp:GridView>

</div>
<asp:label id= "Label1" runat= "Server" text= "Label" ></asp:Label>
</form>
</body>

Codebehind Code for the sample

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 ("total {0} records, per page {1}, page times {2}/{3}", Recordcount,pagesize,pageindex,pagecount);
}


protected void Btnjump_click (object sender, EventArgs e)
{
Int. TryParse (Txtpagesize.text, out pageIndex);
LoadData ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.