星期零

技术改变生活,分享让我们快乐!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net分页是最最常用的功能,实现方式也很多,使用不同的控件有不同的分页方式。

下面分享一个我们团队内部使用了多年的一个分页控件cPage,是自己设计编写,没有冗余,简单、快速。

cPage,现在版本是3.2了,很简单的一个分页功能,可以到这里【下载】。最好是下载这个demo

cPage是asp.net分页控件,也可以叫做分页组件,更确切的应该叫做分页模块,也或者叫做分页通用代码。

cPage,使用url传值实现分页,支持多种asp.net数据控件,如datalist、gridview、Repeater等,支持多种数据源,如SQL Server、Oracle、mysql、DB2等,说的白一点就是能够生成datatable的就可以。

支持url重写(UrlRewrite)分页,比如,常用url分页“info.aspx?p=[#p#]”,url重写“info_[#p#].html”,url中页码是通过“[#p#]”传递的,所以支持任何形式的分页,更多详细请查阅demo。

先来一张效果图:

cPage分装了dll,名称为“cPage.dll”,更重要的是要使用,所以demo很重要。下面是demo的代码:

demo使用了sqlserver2008r2数据库,IDE是vs2010。

demo分页效果图:

sql代码:

CREATE TABLE [info](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[name] [nvarchar](50) NULL,
	[card] [nvarchar](50) NOT NULL,
	[createtime] [datetime] NULL)

demo的页面,cPageList.aspx,代码如下:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="cPageList.aspx.cs" Inherits="cPageList" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">    
    body ,html { font-size:12px;}
    a,table,td,div{font-size:12px; }
    
    a:link {text-decoration: none;}
    a:visited {text-decoration: none;}
    a:hover { text-decoration: none;}
    a:active {text-decoration: none;}
    
    /*-----------------------------------cPage分页css(v3.2)----------------------------------------------*/
    .pagenum{  padding:2px 6px 2px 6px; margin: 0 0 0 4px; text-align:center; border:1px solid #79b7e7;display:inline-block;}
    .pagenum:hover{border:1px solid #f5d37c; background-color:#fdf4de ; text-decoration:none; }
    .pagecur{background-color:#fdf4de; padding:2px 6px 2px 6px; margin: 0 0 0 4px; text-align:center; font-weight:bold; border:1px solid #f5d37c;display:inline-block;}
    .pagecur:hover{border:1px solid #f5d37c; background-color:#fdf4de ; text-decoration:none; }
    .pagecolor{color:#3f3f3f;}
    .pagecolorc{color:#FF6600;font-weight: bold;}
    /*-----------------------------------cPage分页css(v3.2)----------------------------------------------*/
    </style>
    <script language="javascript" type="text/javascript">
        // 鼠标经过改变行的颜色(begin) 
        if (!objbeforeItem) {
            var objbeforeItem = null;
            var objbeforeItembackgroundColor = null;
        }
        function ItemOver(obj) {

            objbeforeItembackgroundColor = obj.style.backgroundColor;
            objbeforeItem = obj;
            obj.style.backgroundColor = "#DDF0FF";
        }
        function ItemOut(obj) {
            if (objbeforeItem) {
                objbeforeItem.style.backgroundColor = objbeforeItembackgroundColor;
            }
        }
        // 鼠标经过改变行的颜色(end)
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table width="630" border="1" cellspacing="0" cellpadding="0" style="border-collapse: collapse;"
            bordercolor="#eaeaea">
            <tr style="text-align: center; height: 30px; font-weight: bold;">
                <td>
                    姓名
                </td>
                <td>
                    身份证号
                </td>
                <td>
                    建立时间
                </td>
                <td width="130">
                    操作
                </td>
            </tr>
            <asp:Repeater ID="cPage_repeaterList" runat="server" OnItemCommand="cPage_repeaterList_ItemCommand"
                OnItemDataBound="cPage_repeaterList_ItemDataBound">
                <ItemTemplate>
                    <tr style="height: 28px; <%# Container.ItemIndex % 2 == 1 ? "background-color:#F7F6F3": ""%>"
                        onmouseover="ItemOver(this)" onmouseout="ItemOut(this)">
                        <td style="padding: 0 0 0 5px">
                            <%# Eval("name")%>
                        </td>
                        <td style="text-align: center;">
                            <%# Eval("card")%>
                        </td>
                        <td style="text-align: center;">
                            <%# Eval("createtime", "{0:yyyy-MM-dd HH:mm:ss}")%>
                        </td>
                        <td style="text-align: center;">
                            <asp:HiddenField ID="hfID" Value='<%#Eval("ID") %>' runat="server" />
                            <a href="userop.aspx?act=up&id=<%# Eval("ID")%>&p=<%=p %>" style="color: Red">【修改】</a>
                            <asp:LinkButton ID="lnkbtnDel" CommandName="del" CommandArgument='<%# Eval("id")%>'
                                Style="color: Red" runat="server">【删除】</asp:LinkButton>
                        </td>
                    </tr>
                </ItemTemplate>
            </asp:Repeater>
        </table>
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td style="text-align: left; height: 50px">
                    <asp:Label ID="lblpage" runat="server"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

 

 

cPageList.aspx.cs代码:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Text.RegularExpressions;

using System.Data;
using System.Configuration;
using System.Data.SqlClient;

using cPage;

public partial class cPageList : System.Web.UI.Page
{
    public int p = 1;   //页码

    protected void Page_Load(object sender, EventArgs e)
    {
        #region 分页获得页码
        string _p = Request.QueryString["p"];

        if (string.IsNullOrEmpty(_p))
            _p = "1";

        if (IsIntType(_p))
        {
            p = Convert.ToInt32(_p);
        }
        else
        {
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "cPageScript", "<script language=\"javascript\" type=\"text/javascript\">alert(\"页码不正确\");history.back();</script>", true);
            return;
        }
        #endregion


        if (!Page.IsPostBack)
        {
            cPageBind();
        }
    }

    protected void cPageBind()
    {
        string _url = Request.FilePath + "?p=[#p#]";
        int _pageNum = 8;           // 中间页码数量
        int _pageSize = 10;         // 每页记录数
        int _beginIndex = 0;        // 开始记录
        int _endIndex = 0;          // 结束记录


        string sqlc = "select count(ID) from info";
        string sqlorder = "order by ID desc";
        string sqltable = "info";


        DataTable DTc = GetDt(sqlc);

        lblpage.Text = mPage.getPage(Convert.ToInt32(DTc.Rows[0][0].ToString()), _pageSize, _pageNum, p, out _beginIndex, out _endIndex, _url);

        //sql server 分页代码(sql server 2005后版本可用)
        string sql = "";

        sql = "WITH NoPagedTable AS (" +
            "SELECT ROW_NUMBER() OVER (" + sqlorder + ") AS rowIndex, " +
            " * " +
            " FROM " + sqltable + " " +
            ")select * from NoPagedTable WHERE rowIndex>=" + _beginIndex + " and rowIndex<=" + _endIndex;
        //

        DataTable DT = GetDt(sql);

        cPage_repeaterList.DataSource = DT;
        cPage_repeaterList.DataBind();

    }

    protected void cPage_repeaterList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemIndex > -1)
        {
            ((LinkButton)e.Item.FindControl("lnkbtnDel")).Attributes["onclick"] = "return confirm('确认要删除吗?');";
        }
    }

    protected void cPage_repeaterList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "del")
        {
            try
            {
                long _ID = Convert.ToInt64(((HiddenField)(e.Item.FindControl("hfID"))).Value);

                string sql = "";

                sql = "delete info where ID=" + _ID;


                int flag = runSQL(sql);

                if (flag == 1)
                {
                    cPageBind();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "cPageScript", "<script language=\"javascript\" type=\"text/javascript\">alert(\"删除失败\");history.back();</script>", true);
            
                }

            }
            catch
            {
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "cPageScript", "<script language=\"javascript\" type=\"text/javascript\">alert(\"数据格式不正确(异常)\");history.back();</script>", true);
            
            }
        }
    }

    /// <summary>
    /// 数据库操作,执行sql语句
    /// </summary>
    /// <param name="inSQL"></param>
    /// <returns></returns>
    public int runSQL(string inSQL)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
        SqlCommand sqlCmd = new SqlCommand(inSQL, conn);

        try
        {
            conn.Open();
            sqlCmd.CommandTimeout = 600;
            sqlCmd.ExecuteNonQuery();
            return 1;
        }
        catch
        {
            return 0;
        }
        finally
        {
            sqlCmd.Dispose();
            conn.Close();
            conn.Dispose();
        }
    }
    
    /// <summary>
    /// 数据库操作,根据sql获取DataTable
    /// </summary>
    /// <param name="inSQL"></param>
    /// <returns></returns>
    public DataTable GetDt(string inSQL)
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
        SqlDataAdapter sqlDA = new SqlDataAdapter(inSQL, conn);
        DataTable outDt = new DataTable();

        conn.Open();
        sqlDA.SelectCommand.CommandTimeout = 600;
        sqlDA.Fill(outDt);

        sqlDA.Dispose();
        conn.Close();
        conn.Dispose();

        return outDt;

    }

    /// <summary>
    /// 判断是否是正整数
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static bool IsIntType(string text)
    {
        Regex reg = new Regex("^[0-9]+$");
        Match ma = reg.Match(text);
        if (ma.Success)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}

  

这里【下载】。最好是下载这个demo

也可以在这里下载:【cPage】    【cPage-demo】


版权所有,bubufx,禁止转载!