Datalist high-efficiency paging algorithm for massive data tables (no stored procedure is used)

Source: Internet
Author: User

First, create a table (the ID is required to be automatically numbered ):
Create Table redheadedfile (
Id int identity (1, 1 ),
Filenames nvarchar (20 ),
Senduser nvarchar (20 ),
Primary Key (ID)
)
Then we write 0.5 million records:
Declare @ I int
Set @ I = 1
While I <= 500000
Begin
Insert into redheadedfile (filenames, senduser) values ('My pagination Algorithm ', 'Ten-level paging algorithmic ')
Set @ I = @ I + 1
End
Go
Use Microsoft Visual Studio. NET 2003 to create a webform webpage (my name is webform8.aspx)
Front-endCodeThe 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>
& Lt; TD width = "30%"

Align = "center"> <% # databinder. eval (container. dataitem, "senduser") %> </TD>
& Lt; 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> pages/Total

<Asp: Label id = "lrecordcount" runat = "server" forecolor = "# ff0000"> </ASP: Label> record
<Asp: linkbutton id = "fistpage" runat = "server"

Commandname = "0"> homepage </ASP: linkbutton> & nbsp; <asp: linkbutton id = "prevpage" runat = "server" commandname = "Prev">

Previous Page </ASP: linkbutton> & nbsp; <asp: linkbutton id = "nextpage" runat = "server"

Commandname = "Next"> next page </ASP: linkbutton> & nbsp; <asp: linkbutton id = "lastpage" runat = "server"

Commandname = "last"> last page </ASP: linkbutton> & nbsp; current <asp: label id = "lcurrentpage" runat = "server"

Forecolor = "# ff0000"> </ASP: Label> page & nbsp; hop <asp: textbox id = "gotopage" runat = "server" width = "30px"

Maxlength = "5" autopostback = "true"> </ASP: textbox> </div>
</Form>
</Body>
</Html>
The background code snippet 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 of 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 records per page
Int pagecount, reccount, currentpage, pages, and jumppage; // defines several parameters for saving paging parameters.

Private void page_load (Object sender, system. eventargs E)
{
If (! Ispostback)
{
Reccount = calc (); // obtain the total number of records through the calc () function
Pagecount = reccount/pagesize + overpage (); // calculate the total number of pages (plus the overpage () function to prevent display due to the remainder

Incomplete Data)

Viewstate ["pagecounts"] = reccount/pagesize-

Modpage (); // Save the total page parameters to viewstate (minus the modpage () function to prevent overflow of the query range during 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. When jumping off a page, determine whether the number of user inputs exceeds the page

Code Range
// Display the status of lpagecount and lrecordcount
Lpagecount. Text = pagecount. tostring ();
Lrecordcount. Text = reccount. tostring ();
// Determines whether the text box on the page is invalid.
If (reccount <= 20)
Gotopage. Enabled = false;
Tdatabind (); // call the data binding function tdatabind () for data binding
}
}
// Calculate the remainder page
Public int overpage ()
{
Int pages = 0;
If (reccount % pagesize! = 0)
Pages = 1;
Else
Pages = 0;
Return pages;
}
// Calculate the remaining page to prevent overflow of the query range during SQL statement execution
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 for using static functions here is: If static data or functions are referenced, the connector will optimize the code generation and remove the dynamic relocation item (

The paging Effect of massive data tables is more obvious ).
* I hope you will give your comments and correct them if they are incorrect.
*/
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 Statement (obtained from web. config)
Public static sqlconnection mycon ()
{
Sqlconnection myconnection = new sqlconnection (configurationsettings. etettings ["DSN"]);
Myconnection. open ();
Return myconnection;
}
// Operate the commandname value returned by the four buttons (Home Page, Previous Page, next page, and last page)
Private void page_onclick (Object sender, commandeventargs E)
{
Currentpage = (INT) viewstate ["pageindex"]; // read the page number value from viewstate and save it to the currentpage variable for parameter operation

Computing
Pages = (INT) viewstate ["pagecounts"]; // calculates the total page parameter read from viewstate.

string cmd = E. commandname;
switch (CMD) // filter commandname
{< br> case "Next":
currentpage ++;
break;
case "Prev":
currentpage --;
break;
case "last":
currentpage = pages;
break;
default:
currentpage = 0;
break;
}< br> viewstate ["pageindex"] = currentpage; // Save the currentpage variable after calculation to viewstate again
tdatabind (); // call the data binding function tdatabind ()
}

Private void tdatabind ()
{
Currentpage = (INT) viewstate ["pageindex"]; // the page number value read from viewstate is saved to the currentpage variable.

Efficiency Calculation
Pages = (INT) viewstate ["pagecounts"]; // read the total page parameters from viewstate for button invalidation Calculation
// Determine the status of the four buttons (Home Page, Previous Page, next page, and last page)
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;
}
// Bind data to the datalist Control
Dataset DS = new dataset ();
// Core SQL statements for query operations (which determines the paging efficiency :))
Sqldataadapter myadapter = new sqldataadapter ("select top" + pagesize + "* From redheadedfile where ID

Not in (select top "+ pagesize * currentpage +" id from redheadedfile order by id asc) order by id asc ", mycon ());
Myadapter. Fill (DS, "news ");
Datalist1.datasource = Ds. Tables ["news"]. defaultview;
Datalist1.databind ();
// Display the status of label controls lcurrentpaget and text box controls gotopage
Lcurrentpage. Text = (currentpage + 1). tostring ();
Gotopage. Text = (currentpage + 1). tostring ();
// Release the sqldataadapter
Myadapter. Dispose ();
}

# Code generated by region web Form Designer
Override protected void oninit (eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
Initializecomponent ();
Base. oninit (E );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content 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
// Page jumping code
Private void gotopage_textchanged (Object sender, system. eventargs E)
{
Try
{
Jumppage = (INT) viewstate ["jumppages"]; // read the Available page number value from viewstate and save it to the jumppage variable
// Determine whether the user input value exceeds the Available page number range
If (int32.parse (gotopage. Text)> jumppage | int32.parse (gotopage. Text) <= 0)

Response. Write ("<SCRIPT> alert ('page number range exceeded! '); Location. href = 'webform8. aspx' </SCRIPT> ");
Else
{
Int inputpage = int32.parse (gotopage. Text. tostring ()-1; // convert the user input values to the int type


viewstate ["pageindex"] = inputpage; // write the inputpage value to viewstate ["pageindex"]
tdatabind (); // call the data binding function tdatabind () perform another data binding operation
}< BR >}< br> // capture exceptions caused by incorrect data types entered by users
catch (exception exp)
{< br> response. write (" ");
}< BR >}

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.