asp.net (C #) High efficiency paging algorithm for mass data tables (no stored procedures are used)

Source: Internet
Author: User
Tags count eval functions sql variables variable tostring visual studio
Asp.net| stored Procedure | pagination | data | algorithm

first create a table (Require ID autonumber):
CREATE TABLE Redheadedfile (
ID int identity (1,1),
Filenames nvarchar (20),
Senduser nvarchar (20),
Primary KEY (ID)
)
then we write 500,000 entries:
DECLARE @i int
Set @i=1
While @i<=500000
Begin
Insert into Redheadedfile (filenames,senduser) VALUES (' My pagination algorithm ', ' Lu Junming ')
Set @i=@i+1
End
Go
Create a WebForm Web page with Microsoft Visual Studio. NET 2003 (my name is webform8.aspx)
The foreground code snippet is as follows (webform8.aspx):
<%@ Page language= "C #" codebehind= "WebForm8.aspx.cs" autoeventwireup= "false" inherits= "WEBAPPLICATION6.WEBFORM8" %>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//en" >
<HTML>
<HEAD>
<title>WebForm8</title>
<meta content= "Microsoft Visual Studio. NET 7.1" name= "generator" >
<meta content= "C #" Name= "Code_language" >
<meta content= "JavaScript" name= "vs_defaultClientScript" >
<meta content= "http://schemas.microsoft.com/intellisense/ie5"Name=" Vs_targetschema ">
</HEAD>
<body ms_positioning= "GridLayout" >
<form id= "Form1" method= "POST" runat= "Server" >
<asp:datalist id= "DataList1" alternatingitemstyle-backcolor= "#f3f3f3" width= "100%" cellspacing= "0"
cellpadding= "0" runat= "Server" >
<ItemTemplate>
<table width= "100%" border= "0" cellspacing= "0" cellpadding= "0" >
<tr>
&LT;TD width= "30%"

align= "center" ><% #DataBinder. Eval (Container.DataItem, "filenames")%></td>
<TD width= "30%"

align= "center" ><% #DataBinder. Eval (Container.DataItem, "Senduser")%></td>
<TD width= "30%"

align= "center" ><% #DataBinder. Eval (Container.DataItem, "id")%></td>
</tr>
</table>
</ItemTemplate>
</asp:datalist>
<div align= "center" > Total <asp:label id= "Lpagecount" runat= "Server" forecolor= "#ff0000" ></asp:label> page /Total

<asp:label id= "Lrecordcount" runat= "Server" forecolor= "#ff0000" ></asp:label> Records
<asp:linkbutton id= "Fistpage" runat= "Server"

Commandname= "0" > Home </asp:linkbutton> <asp:linkbutton id= "prevpage" runat= "Server" Commandname= "prev" >

Previous page </asp:linkbutton> <asp:linkbutton id= "Nextpage" runat= "Server"

Commandname= "Next" > next page </asp:linkbutton> <asp:linkbutton id= "lastpage" runat= "Server"

Commandname= "Last" > End </asp:linkbutton> Current <asp:label id= "Lcurrentpage" runat= "Server"

Forecolor= "#ff0000" ></asp:label> page <asp:textbox id= "gotoPage" runat= "Server" width= "30px"

Maxlength= "5" autopostback= "True" ></asp:TextBox></div>
</form>
</body>
</HTML>
The background code fragment is as follows (Webform8.aspx.cs)
Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Web;
Using System.Web.SessionState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;
Using System.Data.SqlClient;
Using System.Configuration;

Namespace WebApplication6
{
<summary>
Summary description of the WEBFORM8.
</summary>
public class WebForm8:System.Web.UI.Page
{
protected System.Web.UI.WebControls.LinkButton fistpage;
protected System.Web.UI.WebControls.LinkButton prevpage;
protected System.Web.UI.WebControls.LinkButton Nextpage;
protected System.Web.UI.WebControls.LinkButton lastpage;
protected System.Web.UI.WebControls.DataList DataList1;
protected System.Web.UI.WebControls.DropDownList mydroplist;
protected System.Web.UI.WebControls.Label Lpagecount;
protected System.Web.UI.WebControls.Label Lrecordcount;
protected System.Web.UI.WebControls.Label lcurrentpage;
protected System.Web.UI.WebControls.TextBox gotoPage;
const int pagesize=20;//defines the display of records per page
int pagecount,reccount,currentpage,pages,jumppage;//defines several save paging parameter variables

private void Page_Load (object sender, System.EventArgs e)
{
if (! IsPostBack)
{
RecCount = Calc ();//Get total number of records through the Calc () function
PageCount = reccount/pagesize + overpage ()//Total number of pages calculated (plus the overpage () function prevents the display

Incomplete data)

viewstate["pagecounts"] = reccount/pagesize-

Modpage ()//Save the total page parameter to ViewState (minus the modpage () function to prevent the overflow query scope when SQL statement execution, you can use the stored procedure paging algorithm to understand this sentence)
viewstate["PageIndex"] = 0;//Save a page index value of 0 to ViewState
viewstate["jumppages"] = pagecount;//save PageCount to ViewState to determine whether user input exceeds page when skipping page

Code Range
Shows the status of Lpagecount, Lrecordcount
Lpagecount.text = Pagecount.tostring ();
Lrecordcount.text = Reccount.tostring ();
To determine if a page-skipping text box fails
if (RecCount <= 20)
gotopage.enabled = false;
Tdatabind ()//Call data-binding function Tdatabind () for data-binding operations
}
}
Calculate remaining pages
public int Overpage ()
{
int pages = 0;
if (reccount%pagesize!= 0)
pages = 1;
Else
pages = 0;
return pages;
}
Calculate the remaining pages to prevent overflow of query scope when SQL statements are executed
public int Modpage ()
{
int pages = 0;
if (reccount%pagesize = = 0 && reccount!= 0)
pages = 1;
Else
pages = 0;
return pages;
}
/*
* Calculate the static function of the total record
* The reason why I use static functions here is that if you refer to static data or static functions, the connector optimizes the generated code and removes the dynamic relocation item (

Massive data table paging effect is more obvious).
* I hope members will give their views and if they do not have the right points.
*/
public static int Calc ()
{
int RecordCount = 0;
SqlCommand mycmd = new SqlCommand ("SELECT count (*) as CO from redheadedfile", Mycon ());
SqlDataReader dr = Mycmd.executereader ();
if (Dr. Read ())
RecordCount = Int32.Parse (dr["co"). ToString ());
MyCmd.Connection.Close ();
return RecordCount;
}
Database connection statements (obtained from web.config)
public static SqlConnection Mycon ()
{
SqlConnection myconnection = new SqlConnection (configurationsettings.appsettings["DSN"));
Myconnection.open ();
return myconnection;
}
Operation of the CommandName value returned for four buttons (first, Prev, Next, last)
private void Page_onclick (object sender, CommandEventArgs e)
{
currentpage = (int) viewstate["PageIndex"];//reads the page number value from the ViewState and saves it to the currentpage variable for parameter shipment

Count
pages = (int) viewstate["pagecounts"];//reads the total page parameter operation from the ViewState

   string cmd = e.commandname;
   switch (CMD)/filter commandname
   {
    case "Next":
     CurrentPage++;
     break;
    case "prev":
     currentpage--;
     break;
    case "Last":
     currentpage = Pages;
     break;
    default:
     currentpage = 0;
     break;
   }
   viewstate["PageIndex"] = currentpage;//Save the currentpage variable after the operation to ViewState
    tdatabind ()//Call the data-binding function Tdatabind ()
  }

private void Tdatabind ()
{
currentpage = (int) viewstate["PageIndex"];//reads the page number value from the ViewState and saves it to the CurrentPage variable for a button loss

Efficient operation
pages = (int) viewstate["pagecounts"];//reads the total page parameter from the ViewState for the button failure operation
Judge four buttons (first, Prev, Next, last) status
if (currentpage + 1 > 1)
{
Fistpage.enabled = true;
Prevpage.enabled = true;
}
Else
{
fistpage.enabled = false;
prevpage.enabled = false;
}
if (currentpage = = Pages)
{
nextpage.enabled = false;
lastpage.enabled = false;
}
Else
{
Nextpage.enabled = true;
Lastpage.enabled = true;
}
Data binding to DataList controls
DataSet ds = new DataSet ();
Core SQL statements, query operations (determines the efficiency of paging:))
SqlDataAdapter myadapter = new SqlDataAdapter ("Select Top" +pagesize+ "* from Redheadedfile where ID

Not in (select Top "+pagesize*currentpage+" ID from Redheadedfile-ID ASC) ORDER BY ID ASC ", mycon ());
Myadapter.fill (ds, "News");
DataList1. DataSource = ds. tables["News". DefaultView;
DataList1. DataBind ();
Display Label control lcurrentpaget and text box control GoToPage State
Lcurrentpage.text = (currentpage+1). ToString ();
Gotopage.text = (currentpage+1). ToString ();
Release SqlDataAdapter
Myadapter.dispose ();
}

Code generated #region the Web forms Designer
Override protected void OnInit (EventArgs e)
{
//
CodeGen: This call is required for the ASP.net Web forms Designer.
//
InitializeComponent ();
Base. OnInit (e);
}

<summary>
Designer supports required methods-do not use the Code editor to modify
The contents of this method.
</summary>
private void InitializeComponent ()
{
This.Fistpage.Command + = new System.Web.UI.WebControls.CommandEventHandler (this. Page_onclick);
This.Prevpage.Command + = new System.Web.UI.WebControls.CommandEventHandler (this. Page_onclick);
This.Nextpage.Command + = new System.Web.UI.WebControls.CommandEventHandler (this. Page_onclick);
This.Lastpage.Command + = new System.Web.UI.WebControls.CommandEventHandler (this. Page_onclick);
This.gotoPage.TextChanged + = new System.EventHandler (this.gotopage_textchanged);
This. Load + = new System.EventHandler (this. Page_Load);

}
#endregion
Jump page Code
private void Gotopage_textchanged (object sender, System.EventArgs e)
{
Try
{
Jumppage = (int) viewstate["jumppages"];//reads the available page values from ViewState to the jumppage variable
Determines whether user input values exceed the available page range values
if (Int32.Parse (gotopage.text) > Jumppage | | Int32.Parse (Gotopage.text) <= 0)

Response.Write (' <script>alert (' page range! '); location.href= ' webform8.aspx ' </script> ');
Else
{
int inputpage = Int32.Parse (gotoPage.Text.ToString ())-1;//Convert user input value save in int type

In Inputpage variables
viewstate["PageIndex"] = inputpage;//Write inputpage value to viewstate["PageIndex"]
Tdatabind ()//Call data-binding function Tdatabind () data-binding operation again
}
}
Catch exceptions caused by user input of incorrect data type
catch (Exception exp)
{
Response.Write ("<script>alert" ("+exp"). Message+ "'); location.href= ' webform8.aspx ' </script> ');
}
}
}
}

Everyone to try, is the efficiency is much higher?

If there's something wrong, I hope everyone will correct



Related Article

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.