C#高效分页代码(不用存储过程)
首先创建一张表(要求ID自动编号):
create table redheadedfile
(
id int identity(1,1),
filenames nvarchar(50),
senduser nvarchar(50),
primary key(id)
)
然后我们写入50万条记录:
declare @i int
set @i=1
while @i<=500000
begin
insert into redheadedfile(filenames,senduser) values("高效分页算法测试数据" + str(i) ,"广告位招商")
set @i=@i+1
end
GO
用Microsoft Visual Studio .NET 2005创建一张WebForm网页。 前台代码片段如下(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>
<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">共<asp:label id="LPageCount" Runat="server" ForeColor="#ff0000"></asp:label>页/共
<asp:label id="LRecordCount" Runat="server" ForeColor="#ff0000"></asp:label>记录
<asp:linkbutton id="Fistpage" Runat="server" CommandName="0">首页</asp:linkbutton>
<asp:linkbutton id="Prevpage" Runat="server" CommandName="prev">上一页</asp:linkbutton>
<asp:linkbutton id="Nextpage" Runat="server" CommandName="next">下一页</asp:linkbutton>
<asp:linkbutton id="Lastpage" Runat="server" CommandName="last">尾页</asp:linkbutton>
当前第<asp:label id="LCurrentPage" Runat="server" ForeColor="#ff0000"></asp:label>页
跳页<asp:TextBox ID="gotoPage" Runat="server" Width="30px" MaxLength="5" AutoPostBack="True"></asp:TextBox>
</div>
</form>
</body>
</HTML>
后台代码片段如下(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>
/// 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 = ;
//定义几个保存分页参数变量
int PageCount, RecCount, CurrentPage, Pages, JumpPage;
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
//通过Calc()函数获取总记录数
RecCount = Calc();
//计算总页数(加上OverPage()函数防止有余数造成显示数据不完整)
PageCount = RecCount / PageSize + OverPage();
//保存总页参数到ViewState(减去ModPage()函数防止SQL语句执行时溢出查询范围,可以用存储过程分页算法来理解这句)
ViewState["PageCounts"] = RecCount / PageSize - ModPage();
//保存一个为0的页面索引值到ViewState
ViewState["PageIndex"] = ;
//保存PageCount到ViewState,跳页时判断用户输入数是否超出页码范围
ViewState["JumpPages"] = PageCount;
//显示LPageCount、LRecordCount的状态
LPageCount.Text = PageCount.ToString();
LRecordCount.Text = RecCount.ToString();
//判断跳页文本框失效
if (RecCount <= )
{
gotoPage.Enabled = false;
}
//调用数据绑定函数TDataBind()进行数据绑定运算
TDataBind();
}
}
//计算余页
public int OverPage()
{
int pages = ;
if (RecCount % PageSize != )
pages = ;
else
pages = ;
return pages;
}
//计算余页,防止SQL语句执行时溢出查询范围
public int ModPage()
{
int pages = ;
if (RecCount % PageSize == && RecCount != )
pages = ;
else
pages = ;
return pages;
}
// 计算总记录的静态函数
// 本人在这里使用静态函数的理由是:如果引用的是静态数据或静态函数,
// 连接器会优化生成代码,去掉动态重定位项(对海量数据表分页效果更明显)。
// 希望大家给予意见、如有不正确的地方望指正。
public static int Calc()
{
int RecordCount = ;
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;
}
//数据库连接语句(从Web.Config中获取)
public static SqlConnection MyCon()
{
SqlConnection MyConnection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
MyConnection.Open();
return MyConnection;
}
//对四个按钮(首页、上一页、下一页、尾页)返回的CommandName值进行操作
private void Page_OnClick(object sender, CommandEventArgs e)
{
//从ViewState中读取页码值保存到CurrentPage变量中进行参数运算
CurrentPage = (int)ViewState["PageIndex"];
//从ViewState中读取总页参数运算
Pages = (int)ViewState["PageCounts"];
string cmd = e.CommandName;
//筛选CommandName
switch (cmd)
{
case "next":
CurrentPage++;
break;
case "prev":
CurrentPage--;
break;
case "last":
CurrentPage = Pages;
break;
default:
CurrentPage = ;
break;
}
//将运算后的CurrentPage变量再次保存至ViewState
ViewState["PageIndex"] = CurrentPage;
//调用数据绑定函数TDataBind()
TDataBind();
}
private void TDataBind()
{
//从ViewState中读取页码值保存到CurrentPage变量中进行按钮失效运算
CurrentPage = (int)ViewState["PageIndex"];
//从ViewState中读取总页参数进行按钮失效运算
Pages = (int)ViewState["PageCounts"];
//判断四个按钮(首页、上一页、下一页、尾页)状态
if (CurrentPage + > )
{
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;
}
//数据绑定到DataList控件
DataSet ds = new DataSet();
//核心SQL语句,进行查询运算(决定了分页的效率:))
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();
//显示Label控件LCurrentPaget和文本框控件gotoPage状态
LCurrentPage.Text = (CurrentPage + ).ToString();
gotoPage.Text = (CurrentPage + ).ToString();
//释放SqlDataAdapter
MyAdapter.Dispose();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </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
//跳页代码
private void gotoPage_TextChanged(object sender, System.EventArgs e)
{
try
{
//从ViewState中读取可用页数值保存到JumpPage变量中
JumpPage = (int)ViewState["JumpPages"];
//判断用户输入值是否超过可用页数范围值
if (Int32.Parse(gotoPage.Text) > JumpPage || Int32.Parse(gotoPage.Text) <= )
{
Response.Write("<script>alert("页码范围越界!");location.href="WebForm8.aspx"</script>");
}
else
{
//转换用户输入值保存在int型InputPage变量中
int InputPage = Int32.Parse(gotoPage.Text.ToString()) - ;
//写入InputPage值到ViewState["PageIndex"]中
ViewState["PageIndex"] = InputPage;
//调用数据绑定函数TDataBind()再次进行数据绑定运算
TDataBind();
}
}
//捕获由用户输入不正确数据类型时造成的异常
catch (Exception eXP)
{
Response.Write("<script>alert("" + exp.Message + "");location.href="WebForm8.aspx"</script>");
}
}
}
}
C#高效分页代码(不用存储过程)的更多相关文章
- 基于Jquery+Ajax+Json+存储过程 高效分页
在做后台开发中,都会有大量的列表展示,下面给大家给大家分享一套基于Jquery+Ajax+Json+存储过程高效分页列表,只需要传递几个参数即可.当然代码也有改进的地方,如果大家有更好的方法,愿留下宝 ...
- sql server 2000 单主键高效分页存储过程 (支持多字段排序)
sql server 2000 单主键高效分页存储过程 (支持多字段排序) Create PROC P_viewPage /* nzperfect [ ...
- 编写高效Lua代码的方法
编写高效Lua代码的方法 翻译自<Lua Programming Gems>Chapter 2:Lua Performance Tips:Basic fact By Roberto Ier ...
- 怎样编写高效android代码
基于Android相关设备作为嵌入式设备范畴,在书写App应用的时候要格外关注效率.而且受电池电量的限制.这就导致嵌入式设备有诸多考虑.有限处理能力.因此就要求我们尽量去写高效的代码. 本文讨论了非常 ...
- Oracle中经典分页代码!
在Oracle中因为没有top关键字,所以在sqlserver中的分页代码并不适用于Oracle,那么在Oracle中如何来实现分页呢? --查询所有数据 STUNO STUNAME STUAGE S ...
- T-SQL 使用WITH高效分页
一.WITH AS 含义 WITH AS短语,也叫做子查询部分(subquery factoring),可以让你做很多事情,定义一个SQL片断,该SQL片断会被整个SQL语句所用到.有的时候, ...
- 我也谈谈 代码调用存储过程超时,SQL Server Management Studio里运行很快的问题
最近遇到了一个问题就是 一个执行速度很快的存储过程,在代码中调用的时候却超时了. 后来看到了两篇文章: 其中一篇是这样介绍的 今天同事用代码调用存储过程时超时,在SQL Server Manageme ...
- 纯js分页代码(简洁实用)
纯js写的分页代码. 复制代码代码如下: //每页显示字数 PageSize=5000; //分页模式 flag=2;//1:根据字数自动分页 2:根据[NextPage]分页 //默认页 start ...
- PHP分页初探 一个最简单的PHP分页代码实现
PHP分页代码在各种程序开发中都是必须要用到的,在网站开发中更是必选的一项. 要想写出分页代码,首先你要理解SQL查询语句:select * from goods limit 2,7.PHP分页代码核 ...
随机推荐
- JS判断是不是Decimal类型(正则实现)
备忘: function isDecimal(item) { var obj = $(item); if (obj.length > 0) { if ($(obj).val() != null ...
- videojs 视频开发API
videojs就提供了这样一套解决方案,他是一个兼容html5的视频播放工具,早期版本兼容所有浏览器,方法是:提供三个后缀名的视频,并在不支持html5的浏览器下生成一个flash的版本. 最新的3. ...
- Jq超链接提示
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- Maximum Subarray (JAVA)
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
- List小练习
功能:创建链表节点,删除节点,顺序打印,不改变原结构的情况下分别用STL中的stack实现逆序打印和利用函数递归打印 代码如下: //链表问题struct ListNode { int m_nV ...
- mybatis使用order by注意
直接用动态参数生成,不会排序: <if test="orderColumn!=null and orderColumn != ''"> ORDER BY #{order ...
- 转:说说JSON和JSONP
前言 由于Sencha Touch 2这种开发模式的特性,基本决定了它原生的数据交互行为几乎只能通过AJAX来实现. 当然了,通过调用强大的PhoneGap插件然后打包,你可以实现100%的Socke ...
- 中国大学MOOC-翁恺-C语言程序设计习题集
今年网易出了“中国大学MOOC”,于是选了浙大翁恺老师的“C语言程序设计”学习,近期打算把自己在该课程中的PAT习题解答做一个记录,等自己编程能力提高后再来看现在写的代码哪里还有写的不好,可以改进的地 ...
- SQL Server 内存压力解决方案
外部压力: 表现形式: 1.total server memory ↓ 2.avilable Mbyte 平衡 3.working set ↓ 如果说SQ ...
- 致终将火爆的NFC——ISO14443 TypeA
毫无疑问,当NFC终端越来越普及,逐渐成为智能手机标配功能后,我们终将迎来NFC的火爆.国内NFC应用最为广泛的将是TypeA,如Mifare.NFC Tag.移动支付等,所以接下来将主要研究Type ...