posts - 58,  comments - 121,  trackbacks - 30

首先说明下:并非全部本人原创,大部分参考了别人的代码,我只是修正了一点bug而已。
--------------------------------------------------------------------------------------------------------
前台代码:
------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="News_test" %>

<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <TABLE id="Table1" style="Z-INDEX: 101; LEFT: 32px; WIDTH: 752px; POSITION: absolute; TOP: 16px; HEIGHT: 312px" cellSpacing="0" cellPadding="0" width="752" border="0">
            <TR>
                <TD style="HEIGHT: 29px"><FONT face="宋体">DataList分页技术和超级链接</FONT></TD>
            </TR>
            <TR>
                <TD style="HEIGHT: 252px">
                <asp:datalist id="DataList1" runat="server" Width="576px" Height="96px">
                     <HeaderTemplate>
                            定单编号<td>
                            员工编号<td>
                            定单日期<td>
                            运费<td>
                            运往所在城市
                     </HeaderTemplate>

                     <ItemTemplate>
                        <%# DataBinder.Eval(Container.DataItem,"OrderID")%> <td>
                        <%# DataBinder.Eval(Container.DataItem,"CustomerID")%> <td>
                        <%# DataBinder.Eval(Container.DataItem,"OrderDate")%> <td>
                        <%# DataBinder.Eval(Container.DataItem,"Freight")%>  <td>
                        <%# DataBinder.Eval(Container.DataItem,"ShipCity")%>
                     </ItemTemplate>
                 </asp:datalist>
                 </TD>
                </TR>
                <TR>
                    <TD><FONT face="宋体">

            <asp:linkbutton id="FirstLB" runat="server" OnCommand="LinkButton_Click" CommandName="first">第一页</asp:linkbutton>&nbsp;
            <asp:linkbutton id="PreviousLB" runat="server" OnCommand="LinkButton_Click" CommandName="prev">上一页</asp:linkbutton>&nbsp;
            <asp:linkbutton id="NextLB" runat="server" OnCommand=LinkButton_Click CommandName="next">下一页</asp:linkbutton>&nbsp;
            <asp:linkbutton id="EndLB" runat="server" OnCommand=LinkButton_Click CommandName="end">最后一页</asp:linkbutton>&nbsp;&nbsp;
            总<asp:label id="TotalLbl" runat="server"></asp:label>页 当前第<asp:label id="CurrentLbl" runat="server"></asp:label>页
            <asp:linkbutton id="JumpLB" runat="server" OnCommand=LinkButton_Click CommandName="jump">跳到</asp:linkbutton>第
            <asp:textbox id="TextBox1" runat="server" Width="90px"></asp:textbox>
            页</FONT></TD>
            </TR>
            </TABLE>
    </div>
    </form>
</body>
</html>
-------------------------------------------------
后台代码:
----------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class News_test : System.Web.UI.Page
{
    int CurrentPage;//当前页数
    int PageSize;   //每页条数
    int PageCount;  //总页数
    int RecordCount;//总条数
    private void Page_Load(object sender, System.EventArgs e)
    {
        // 在此处放置用户代码以初始化页面


        PageSize = 10;//每页10条记录
       

        if (!Page.IsPostBack)
        {            
             CurrentPage = 0;//当前页习惯设为0
            ViewState["PageIndex"] = 0;//页索引也设为0


            //计算总共有多少记录
            RecordCount = CalculateRecord();


            //计算总共有多少页
            if (RecordCount % PageSize == 0)
            {
                PageCount = RecordCount / PageSize;
            }
            else
            {
                PageCount = RecordCount / PageSize + 1;
            } 

            this.TotalLbl.Text = PageCount.ToString();//显示总页数
            ViewState["PageCount"] = PageCount;//会话session 对整个 application 有效 ,而视图状态 viewstate相当于某个页面的 session

            this.DataListBind();//不可以放在初始化条件之前就绑定,那样的话,如果仅有一页的数据,“下一页”页仍然显示
            
        }


    }


    //计算总共有多少条记录
    private int CalculateRecord()
    {
        try
        {
            int recordCount;
            SqlConnection con = new SqlConnection("server=127.0.0.1;database=Northwind;uid=sa;pwd=sa");//数据库使用Northwind;
            con.Open();

            string sql = "select count(*) as count from Orders";
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataReader sdr = cmd.ExecuteReader();

            if (sdr.Read())
            {
                recordCount = Int32.Parse(sdr["count"].ToString());               
            }


            else
            {
                recordCount = 0;
            }

            sdr.Close();
            con.Close();
            return recordCount;
        }


        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }


    //将数据绑定到Datalist控件
    public void DataListBind()
    {
        try
        {
            int StartIndex = CurrentPage * PageSize;//设定导入的起终地址
            string sql = "select * from Orders";
            DataSet ds = new DataSet();
            SqlConnection con = new SqlConnection("server=127.0.0.1;database=Northwind;uid=sa;pwd=sa");
            con.Open();

            SqlDataAdapter sda = new SqlDataAdapter(sql, con);
            sda.Fill(ds, StartIndex, PageSize, "orders");//这是sda.Fill方法的第一次重载,里面的变量分别是数据集DataSet ,开始记录数StartRecord,最大的记录数MaxRecord,数据表名TableName
            this.DataList1.DataSource = ds.Tables["orders"].DefaultView;
            this.DataList1.DataBind();
            this.PreviousLB.Enabled = true;
            this.NextLB.Enabled = true;
            if (CurrentPage == (PageCount - 1)) this.NextLB.Enabled = false;//当为最后一页时,下一页链接按钮不可用
            if (CurrentPage == 0) this.PreviousLB.Enabled = false;//当为第一页时,上一页按钮不可用
            this.CurrentLbl.Text = (CurrentPage + 1).ToString();//当前页数

        }


        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

  


    public void LinkButton_Click(Object sender, CommandEventArgs e)//自己编写的按钮点击事件
    {
        CurrentPage = (int)ViewState["PageIndex"];//获得当前页索引
        PageCount = (int)ViewState["PageCount"];//获得总页数


        string cmd = e.CommandName;

        //判断cmd,以判定翻页方向


        switch (cmd)
        {
            case "prev"://上一页
                if (CurrentPage > 0) CurrentPage--;
                break;

            case "next":
                if (CurrentPage < (PageCount - 1)) CurrentPage++;//下一页
                break;

            case "first"://第一页
                CurrentPage = 0;
                break;

            case "end"://最后一页
                CurrentPage = PageCount - 1;
                break;

            case "jump"://跳转到第几页
                if (this.TextBox1.Text.Trim() == "" || Int32.Parse(this.TextBox1.Text.Trim()) > PageCount)//如果输入数字为空或超出范围则返回
                {
                    return;
                }
                else
                {                   
                    CurrentPage = Int32.Parse(this.TextBox1.Text.ToString()) - 1;
                    break;
                }
        }
        ViewState["PageIndex"] = CurrentPage;//获得当前页

        this.DataListBind();//重新将DataList绑定到数据库


    }

}

------------------------
实际使用的时候,要对“跳转”到的文本框输入值进行正整数的验证。

posted on 2006-12-29 11:47 datasky 阅读(1798) 评论(7)  编辑 收藏 网摘 所属分类: ASP.NET

FeedBack:
2007-12-19 18:11 | gfdsg [未注册用户]
fdsa
  回复  引用    
2007-12-30 18:14 | 隋心所欲 [未注册用户]
http://www.tobrush.com/archives/617301
楼主真强啊!这篇文章详细说明了如何使用DataList进行分页
  回复  引用    
2008-10-19 10:37 | 广告歌 [未注册用户]
很好
  回复  引用    
2008-10-24 11:04 | NICE [未注册用户]
嗯,同意楼上的观点,的确很不错。
不过有个bug,就是当你删除或添加一条或多条数据后,页数未重新计算!
  回复  引用    
2008-10-24 11:09 | NICE [未注册用户]
建议楼主在PageLoad事件里面把判断页面是否首次加载给取消。
  回复  引用    
2008-11-06 21:38 | freeis.bokee.com [未注册用户]
好好好!太棒了,谢谢!
  回复  引用    




标题  
姓名  
主页
Email (博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2006-12-29 18:03 编辑过
Google站内搜索


China-pub 计算机图书网上专卖店!6.5万品种 2-8折!
近千种 9-95 新二手计算图书火热销售中!

相关文章:

相关链接:
 

欢迎加入Asp.net高手MSN群

  • asp.net.group#hotmail.com
  • asp.net_group#hotmail.com

与我联系

搜索

 

常用链接

留言簿

我管理的小组

我的标签

随笔分类(71)

相册

blogs链接

积分与排名

  • 积分 - 35317
  • 排名 - 1299

最新评论