gridview是asp.net常用的显示数据控件,对于.net开发人员来说应该是非常的熟悉了。gridview自带有许多功能,包括分页,排序等等,但是作为一个.net开发人员来说熟练掌握利用存储过程分页或者第三方自定义分页十分重要,这不仅是项目的需要,也是我们经验能力的提示,下面我就来讲利用存储过程分页实现绑定gridview

1  执行存储过程

网上有许多sql分页存储过程的例子,但是你会发现其中有许多一部分是不能用的,例如有些使用in或者not in来分页效率非常的低,有些sp可以分页但是扩展型非常差,有些效率也比较高,但是不能返回查询记录总数,

例如下面的这个分页,尽管比较简单,但是用not in来分页效率比较低,且查询表已经固定死了,无法扩展,其实是个失败的分页

CREATE PROCEDURE GetProductsByPage
@PageNumber int,
@PageSize int
AS
declare @sql nvarchar(4000)
set @sql = 'select top ' + Convert(varchar, @PageSize)   + ' * from test where id not in (select top ' + Convert(varchar, (@PageNumber - 1) * @PageSize)  + ' id from test)'
exec sp_executesql @sql
GO

 综上我觉得这个分页总体上来说比较好的效率也非常的高且分页只需要执行一次sp,分页支持多表多标间查询

ALTER PROCEDURE [dbo].[Proc_SqlPageByRownumber](@tbName VARCHAR(255),            --表名@tbGetFields VARCHAR(1000)= '*',--返回字段@OrderfldName VARCHAR(255),        --排序的字段名@PageSize INT=20,               --页尺寸@PageIndex INT=1,               --页码@OrderType bit = 0,                --0升序,非0降序@strWhere VARCHAR(1000)='',     --查询条件@TotalCount INT OUTPUT            --返回总记录数)AS-- =============================================-- Author:      allen (liyuxin)-- Create date: 2012-03-30-- Description: 分页存储过程(支持多表连接查询)-- Modify [1]:  2012-03-30-- =============================================BEGINDECLARE @strSql VARCHAR(5000)    --主语句DECLARE @strSqlCount NVARCHAR(500)--查询记录总数主语句DECLARE @strOrder VARCHAR(300) -- 排序类型--------------总记录数---------------IF ISNULL(@strWhere,'') <>''SET @strSqlCount='Select @TotalCout=count(*) from  ' + @tbName + ' where 1=1 '+ @strWhereELSE SET @strSqlCount='Select @TotalCout=count(*) from  ' + @tbNameexec sp_executesql @strSqlCount,N'@TotalCout int output',@TotalCount output--------------分页------------IF @PageIndex <= 0 SET @PageIndex = 1IF(@OrderType<>0) SET @strOrder=' ORDER BY '+@OrderfldName+' DESC 'ELSE SET @strOrder=' ORDER BY '+@OrderfldName+' ASC 'SET @strSql='SELECT * FROM (SELECT ROW_NUMBER() OVER('+@strOrder+') RowNo,'+ @tbGetFields+' FROM ' + @tbName + ' WHERE 1=1 ' + @strWhere+' ) tb WHERE tb.RowNo BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND ' +str(@PageIndex*@PageSize)exec(@strSql)SELECT @TotalCountEND

2   封装c#调用语句

我们总是习惯上对代码进行封装,这样可以提高代码的阅读效率,维护起来也更加方便,养成良好的封装代码习惯,我们就从初级步入了中级,其实这只是个习惯而已

   public static class PageHelper{/// <summary>/// 分页数据/// </summary>/// <param name="TableName">表明</param>/// <param name="RetureFields">返回字段</param>/// <param name="strWhere">条件</param>/// <param name="PageSize">每页记录数</param>/// <param name="CurPage">当前页数</param>/// <param name="RowCount">总记录数</param>/// <param name="sortField">排序字段</param>/// <returns></returns>public static DataTable GetPageList(string tbName, string tbGetFields, string OrderFldName, int PageSize, int PageIndex, int OrderType, string strWhere, out int TotalCount){SqlCommand cmd = new SqlCommand("Proc_SqlPageByRownumber");//存储过程名称cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.AddWithValue("@tbName", tbName);//表名称cmd.Parameters.AddWithValue("@tbGetFields", tbGetFields);//要显示的字段名(不要加Select)cmd.Parameters.AddWithValue("@OrderfldName", OrderFldName);//排序索引字段名cmd.Parameters.AddWithValue("@PageIndex", PageIndex);//当前第几页,页码cmd.Parameters.AddWithValue("@PageSize", PageSize);//每页显示的数据条数cmd.Parameters.AddWithValue("@OrderType", OrderType);//设置排序类型,非0值则降序cmd.Parameters.AddWithValue("@strWhere", strWhere);//查询条件,不要加wherecmd.Parameters.Add(new SqlParameter("@TotalCount", SqlDbType.Int));cmd.Parameters["@TotalCount"].Direction = ParameterDirection.Output;DataTable dt = RunProcedureCmd(cmd);TotalCount = Convert.ToInt32(cmd.Parameters["@TotalCount"].Value.ToString());//返回的总页数return dt;}/// <summary>/// 执行存储过程,返回DataTable/// </summary>/// <param name="cmd"></param>/// <returns></returns>public static DataTable RunProcedureCmd(SqlCommand cmd){DataTable result = new DataTable();string connectionString = ConfigurationManager.AppSettings["CONNSTRING"].ToString();SqlConnection conn = new SqlConnection(connectionString);//你自己的链接字符串try{if ((conn.State == ConnectionState.Closed)){conn.Open();}cmd.Connection = conn;SqlDataAdapter da = new SqlDataAdapter(cmd);da.Fill(result);da.Dispose();conn.Close();conn.Dispose();return result;}catch (Exception ex){conn.Close();conn.Dispose();throw ex;}}  }

  3  gridview利用第三方插件实现分页

分页现在比较流行的插件是aspnetpager,这是一个比较成熟的插件,网上也有许多的例子。

1 下载aspnetpager插件,然后右键引用。

2  打开工具箱,在选项卡上右键选择项导入插件

3 拖控件到页面,设置控件的属性

后台代码

protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){GridViewBind("");}}private void GridViewBind(string sqlWhere){int TotalCount;DataTable dt = bll.GetList("stu_score", "code,name,beginTime,endTime,score", "id", this.AspNetPager1.PageSize, this.AspNetPager1.CurrentPageIndex, 1,sqlWhere, out TotalCount);this.AspNetPager1.RecordCount = TotalCount;this.GridView1.DataSource = dt;this.GridView1.DataBind();this.AspNetPager1.CustomInfoHTML = string.Format("当前第{0}/{1}页 共{2}条记录 每页{3}条", new object[] { this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageCount, this.AspNetPager1.RecordCount, this.AspNetPager1.PageSize });     }//GridView高亮行显示 protectedvoid GridView1_RowDataBound1(object sender, GridViewRowEventArgs e)  {  if (e.Row.RowType == DataControlRowType.DataRow)  {  e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor,this.style.backgroundColor='#C7DEF3'");  e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");  }  }

  

前台代码

        <table width="100%"><tr><td style="width: 60%; float: left;">beginTime:<asp:TextBox ID="txtBeginTime" runat="server"></asp:TextBox>endTime:<asp:TextBox ID="txtEndTime" name="mydate" runat="server"></asp:TextBox></td><td style="width: 30%; float: right;"><asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click"class="ui-button ui-widget ui-state-default ui-corner-all"></asp:Button>  <asp:Button ID="btnAdd" runat="server" Text="Create" OnClientClick="javascript:return false;" /></td></tr><tr><td colspan="2" style="width: 100%; float: left;"><asp:GridView ID="GridView1" runat="server" Width="100%" CellPadding="2" CssClass="GridViewStyle"CellSpacing="2" AutoGenerateColumns="False"><Columns><asp:BoundField DataField="name" HeaderText="name" /><asp:BoundField DataField="code" HeaderText="code" /><asp:BoundField DataField="beginTime" HeaderText="beginTime" /><asp:BoundField DataField="endTime" HeaderText="endTime" /><asp:BoundField DataField="score" HeaderText="score" /></Columns><FooterStyle CssClass="GridViewFooterStyle" /><RowStyle CssClass="GridViewRowStyle" /><SelectedRowStyle CssClass="GridViewSelectedRowStyle" /><PagerStyle CssClass="GridViewPagerStyle" /><AlternatingRowStyle CssClass="GridViewAlternatingRowStyle" /><HeaderStyle CssClass="GridViewHeaderStyle" /></asp:GridView></td></tr><tr><td colspan="2"><webdiyer:AspNetPager ID="AspNetPager1" runat="server" CssClass="paginator" CurrentPageButtonClass="cpb"OnPageChanged="AspNetPager1_PageChanged" PageSize="5" FirstPageText="首页" LastPageText="尾页"NextPageText="下一页" PrevPageText="上一页" CustomInfoHTML="共%RecordCount%条,第%CurrentPageIndex%页 /共%PageCount% 页"CustomInfoSectionWidth="30%" ShowCustomInfoSection="Right"></webdiyer:AspNetPager></td></tr></table>

  

4 当然你可以对你的gridview进行样式调整,新建gridviewSY.css

.GridViewStyle
{   border-right: 2px solid #A7A6AA;border-bottom: 2px solid #A7A6AA;border-left: 2px solid white;border-top: 2px solid white;padding: 4px;
}
.GridViewStyle a
{color: #FFFFFF;
}.GridViewHeaderStyle th
{border-left: 1px solid #EBE9ED;border-right: 1px solid #EBE9ED;
}.GridViewHeaderStyle
{background-color: #5D7B9D;font-weight: bold;color: White;
}.GridViewFooterStyle
{background-color: #5D7B9D;font-weight: bold;color: White;
}.GridViewRowStyle
{background-color: #F7F6F3;color: #333333;
}.GridViewAlternatingRowStyle
{background-color: #FFFFFF;color: #284775;
}.GridViewRowStyle td, .GridViewAlternatingRowStyle td
{border: 1px solid #EBE9ED;
}.GridViewSelectedRowStyle
{background-color: #E2DED6;font-weight: bold;color: #333333;
}.GridViewPagerStyle
{background-color: #284775;color: #FFFFFF;
}.GridViewPagerStyle table /* to center the paging links*/
{margin: 0 auto 0 auto;

分页控件也添加样式,当然gridview样式和分页样式在同一个css中了

.paginator { font: 11px Arial, Helvetica, sans-serif;padding:10px 20px10px 0; margin: 0px;}
.paginator a {padding: 1px 6px; border: solid 1px #ddd; background:#fff; text-decoration: none;margin-right:2px}
.paginator a:visited {padding: 1px 6px; border: solid 1px #ddd;background: #fff; text-decoration: none;}
.paginator .cpb {padding: 1px 6px;font-weight: bold; font-size:13px;border:none}
.paginator a:hover {color: #fff; background: #ffa501;border-color:#ffa501;text-decoration: none;}

 页面最总结果显示样式,

 

接下来我们给时间添加样式,给时间添加样式普遍选择的是datePicker插件,导入控件所用的js和css

<script src="jquery-ui-1.9.2.custom/js/jquery-1.8.3.js" type="text/javascript"></script>
<script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.widget.js" type="text/javascript"></script>
<script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.core.js" type="text/javascript"></script>
<script src="jquery-ui-1.9.2.custom/development-bundle/ui/jquery.ui.datepicker.js" type="text/javascript"></script><link href="jquery-ui-1.9.2.custom/development-bundle/themes/ui-lightness/jquery.ui.all.css" rel="stylesheet" type="text/css" />

默认时间插件显示的是英文,我们给他汉化

新建initdatepicker_cn.js

function initdatepicker_cn() {$.datepicker.regional['zh-CN'] = {clearText: '清除',clearStatus: '清除已选日期',closeText: '关闭',closeStatus: '不改变当前选择',prevText: '<上月',prevStatus: '显示上月',prevBigText: '<<',prevBigStatus: '显示上一年',nextText: '下月>',nextStatus: '显示下月',nextBigText: '>>',nextBigStatus: '显示下一年',currentText: '今天',currentStatus: '显示本月',monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],monthStatus: '选择月份',yearStatus: '选择年份',weekHeader: '周',weekStatus: '年内周次',dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],dayStatus: '设置 DD 为一周起始',dateStatus: '选择 m月 d日,DD',dateFormat: 'yy-mm-dd',firstDay: 1,initStatus: '请选择日期',isRTL: false};$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
}

  前台页面添加jquery脚本,当然MainContent_txtBeginTime是你时间标签的id,有时候你可能显示不出来,不要着急右键查看源文件就会发现控件的id和html标签的id不一样,我们一定要选择标签的id

    <script type="text/javascript">jQuery(function () {initdatepicker_cn();$('#MainContent_txtBeginTime').datepicker({ changeMonth: true, changeYear: true });});</script>

  效果图

如果你按照这四步去做的话,一个简单实用的分页显示页面就会展现的你的面前,欢迎博客园大佬提意见。随时讨论

转载于:https://www.cnblogs.com/f23wangj/archive/2013/06/07/3124933.html

利用aspnetPager控件加存储过程实现对gridview的分页相关推荐

  1. 利用tab_control控件在对话框中加入属性页的方法详细介绍

    在对话框中加入属性页 方案一 在对话框上放置一个Tab Control的控件,再在对话框上放置所需的控件(本例放置了2个按钮,试图在每个标签中显示一个).然后利用Class Wizard来为Tab C ...

  2. webdiyer:AspNetPager控件样式设置

    在做项目时候需要修改webdiyer:AspNetPager分页控件的样式,查找了很多资料.总结如下. 1.引入样式表. 将想要使用的样式表加入到本页面<styletype="text ...

  3. Go web 开发数据库管理平台,利用远程过程调用(RPC)实现对MySQL数据库的管理和使用

    Go web 开发数据库管理平台,利用远程过程调用(RPC)实现对MySQL数据库的管理和使用 前言 做DBA,最基本的工作就是需要管理公司的数据库系统.工作中,常常需要维护的数据库数量是非常多的.小 ...

  4. ASP中利用OWC控件实现图表功能详解[zz]

    ASP中利用OWC控件实现图表功能详解 在ASP中利用OWC(Office Web Components)控件可轻松实现各种图表功能,如饼图,簇状柱型图,折线图等. 在下面的代码中我详细的给出了饼图, ...

  5. Delphi利用MSCOMM控件进行GPS数据采集

    1.准备 GPS(Global Positioning System),即全球定位系统,利用GPS卫星的测距和测时功能进行全球定位,在许多系统中,如机场导航系统,出租车辆管理和调度系统.江河流域的灾害 ...

  6. paip.gui控件tabs控件加载内容的原理以及easyui最佳实现

    paip.gui控件tabs控件加载内容的原理以及easyui最佳实现 //tabs控件的加载 同form窗体一样,俩个方式 两个方式:一个是url,简单的文本可以使用这个,不适合事件的情形.. 一个 ...

  7. 利用SiteMapPath控件做论坛导航

    利用SiteMapPath控件做论坛导航(也适合其它系统) 首先,论坛非常简单,就三个网页,全部用的一个模板做成. 第一个网页(default.aspx):用于显示论坛的类别,点击相应的类别,将cat ...

  8. Windows10下VB6.0开发——利用PictureBox控件实现数据点实时绘图

    前言:VB中可以利用PictureBox控件实现数据点实时绘图功能. 1. 控件PictureBox   下面是PictureBox的图标:   将该控件拖到目标位置后调整它的形状大小,修改它的背景色 ...

  9. C#利用Picturebox控件显示图片

    源文章:https://blog.csdn.net/liyuqian199695/article/details/54098938 C#利用Picturebox控件显示图片 1.Picturebox控 ...

最新文章

  1. eb8000软件怎样上传_百度网盘如何免费上传超过4G的文件?BitComet来帮你!
  2. 【python基础知识】python输出时出错,UnicodeEncodeError: 'gbk' codec can't encode character '\ue4bf.....
  3. iOS开发计算工程里面的代码行数
  4. 火狐扩展插件开发者模式_使用插件扩展您的开发人员社区
  5. 实施工程师的发展前景
  6. ansys 命令流基础—— 点线面体基本操作
  7. 自定义video标签的大小
  8. arm linux游戏手柄(joystick)驱动移植
  9. 不想充文库会员(百度文库,360文库等),又急需复制粘贴咋整?JavaScript一键解决
  10. win10系统的计算机C盘在哪,win10系统电脑C盘programdata在哪的图文办法
  11. mysql-8.0.16-winx64_mysql-8.0.16-winx64的最新安装教程
  12. linux查看操作系统版本的命令
  13. 安全测试涉及的测试对象有哪些?
  14. 【Pandas处理CSV】Error tokenizing data. C error: Expected 1 fields in line XX, saw XX
  15. Linux服务器下挂载存储
  16. 同或门(XNOR)电路的网络学习
  17. CentOS8配置NTP服务器同步Windows和Linux主机
  18. B2B2C/B2B/B2C商城源码
  19. Drupal7_1:初识drupal
  20. 人生第一个扩展——Github1s

热门文章

  1. Flask make_response(*args)
  2. flask-bootstrap插件
  3. Bokeh 布局图像和工具
  4. 数据算法之折半查找(binSearch)的Java实现
  5. CDM是什么?和CDP有什么区别?
  6. 审计文件服务器的5个核心要素
  7. 一台弹性云服务器可以挂载多块磁盘吗?
  8. Redis学习总结(23)——Redis如何实现故障自动恢复?浅析哨兵的工作原理
  9. Linux学习总结(24)——Linux查找文件命令
  10. 阿里巴巴开源技术汇总:115个软件(二)