datalist控件的分页(下载示例与自己改写示例)

  1、参考示例
<%@ 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">宋体">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">宋体">
            <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绑定到数据库
    }

}

 2、自己改写示例

 

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

<! 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 >
            
< tr >
                
< td  style ="width: 618px" >
                    
< asp:Label  ID ="Label2"  runat ="server"  Text ="Label"  Width ="427px" ></ asp:Label ></ td >
            
</ tr >
            
< tr >
                
< td  style ="width: 618px; height: 223px" >
                    
< asp:DataList  ID ="DataList1"  runat ="server"  Width ="615px" >
                        
< ItemTemplate >
                            
< table >
                                
< tr >
                                    
< td  style ="width: 25px; height: 22px; color: blue;" >
                                        •
</ td >
                                    
< td  style ="width: 1552px; height: 22px" >
                                        
< asp:LinkButton  ID ="LinkButton1"  runat ="server" > <% #DataBinder.Eval(Container.DataItem,"title") %> </ asp:LinkButton ></ td >
                                    
< td  style ="width: 438px; height: 22px" >
                                        
< asp:Label  ID ="Label1"  runat ="server" > <% #((DateTime)DataBinder.Eval(Container.DataItem, "adddate")).ToShortDateString() %> </ asp:Label ></ td >
                                
</ tr >
                            
</ table >
                        
</ ItemTemplate >
                    
</ asp:DataList ></ td >
            
</ tr >
            
< tr >
                
< td  style ="width: 618px; text-align: center;" >
                    
< asp:Label  ID ="lbpage"  runat ="server"  Text ="Label" ></ asp:Label >
                    
&nbsp;   &nbsp; < asp:LinkButton  ID ="lbfirst"  runat ="server"  CommandName ="first"  OnCommand ="linkbuttoncmd" > 首页 </ asp:LinkButton >
                    
< asp:LinkButton  ID ="lbprev"  runat ="server"  CommandName ="prev"  OnCommand ="linkbuttoncmd" > 上一页 </ asp:LinkButton >
                    
< asp:LinkButton  ID ="lbnext"  runat ="server"  CommandName ="next"  OnCommand ="linkbuttoncmd" > 下一页 </ asp:LinkButton >
                    
< asp:LinkButton  ID ="lblast"  runat ="server"  CommandName ="last"  OnCommand ="linkbuttoncmd" > 末页 </ asp:LinkButton > &nbsp;
                    
&nbsp;&nbsp;
                    
< asp:TextBox  ID ="tb"  runat ="server"  Width ="46px" ></ asp:TextBox >
                    
< asp:LinkButton  ID ="lbjump"  runat ="server"  CommandName ="jump"  OnCommand ="linkbuttoncmd" > 跳转 </ asp:LinkButton ></ 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  newslist : System.Web.UI.Page
{
    BaseClass bc
=new BaseClass();
    pagechange pc 
= new pagechange();
    
string strstyle;


    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!IsPostBack)
        
{
            
int n = Convert.ToInt32(Request.QueryString["id"]);
            
switch (n)
            
{
                
case 1: strstyle = "type='企业新闻'";
                    Label2.Text 
= "足不出户->企业新闻";
                    
break;
                
case 2: strstyle = "type='行业新闻'";
                    Label2.Text 
= "足不出户->行业新闻";
                    
break;
                
case 3: strstyle = "type='社会新闻'";
                    Label2.Text 
= "足不出户->社会新闻";
                    
break;
                
default: strstyle = "type like '%%'";
                    Label2.Text 
= "所有新闻";
                    
break;
            }



            pc.cmd 
= "select count(*) as count from tbnews where " + strstyle;
            pc.RecordCount();
            pc.PageCount();
            pc.sql 
= "select * from tbnews where " + strstyle;
            pc.databind(DataList1, lbprev, lbnext, lbpage);


            
//与 Session 的重要区别有两个:
            
//第一、ViewState 保存的对象不能跨页使用,仅限当前页面使用。Session 对象则可以所有页面共享使用。
            
//第二、Session 的变量存储在服务器上,ViewState 存储在当前页面中。
            ViewState["pagecount"= pc.pagecount;//ViewState 保存的对象不能跨页使用,仅限当前页面使用.而
            ViewState["currentpage"= pc.currentpage;
            ViewState[
"sql"= pc.sql;
        }

        
else
        
{
            pc.pagecount 
= int.Parse(ViewState["pagecount"].ToString());
            pc.currentpage 
= int.Parse(ViewState["currentpage"].ToString());
            pc.sql 
= ViewState["sql"].ToString();
        }

    }



    
protected void linkbuttoncmd(Object sender, CommandEventArgs e)//自己编写的按钮点击事件
    {
        
switch (e.CommandName)
        
{
            
case "first":
                pc.currentpage 
= 0;
                
break;
            
case "prev":
                
if (pc.currentpage > 0{ pc.currentpage = pc.currentpage - 1; }
                
break;
            
case "next":
                
if (pc.currentpage < pc.pagecount - 1{ pc.currentpage = pc.currentpage + 1; }
                
break;
            
case "last":
                pc.currentpage 
= pc.pagecount - 1;
                
break;
            
case "jump":
                
if (tb.Text.Trim() == "" || int.Parse(tb.Text.Trim()) < 0 & int.Parse(tb.Text.Trim()) > pc.pagecount - 1)
                
{
                    
return;
                }

                
else
                
{
                    pc.currentpage 
= int.Parse(tb.Text.Trim()) - 1;
                }

                
break;
        }

        ViewState[
"currentpage"= pc.currentpage;
        pc.databind(DataList1, lbprev, lbnext, lbpage);
    }



        
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
    
{
        
string id = DataList1.DataKeys[e.Item.ItemIndex].ToString();
        Response.Write(
"<script language=javascript>window.open('showNews.aspx?id=" + id + "','','width=520,height=260')</script>");             
    }

}


 

pagechange类

 

using System;
using System.Data;
using System.Configuration;
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;
/// <summary>
/// pagechange 的摘要说明
/// </summary>
public class pagechange
{
    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
    public int _recordcount;//定义记录数
    public int _pagecount;//定义页数
    public string _cmd;
    public string _sql;
    public int _pagesize = 10;//每页显示的记录数
    public int _currentpage = 0;//当前页的索引

    public pagechange()
 {
  //
  // TODO: 在此处添加构造函数逻辑
  //
 }

    //定义有关的属性
    public int recordcount
    {
        get { return _recordcount; }
        set { _recordcount = value; }
    }
    public int pagecount
    {
        get { return _pagecount; }
        set { _pagecount = value; }
    }
    public string cmd
    {
        get { return _cmd; }
        set { _cmd = value; }
    }
    public string sql
    {
        get { return _sql; }
        set { _sql = value; }
    }
    public int pagesize
    {
        get { return _pagesize; }
        set { _pagesize = value; }
    }
    public int currentpage
    {
        get { return _currentpage; }
        set { _currentpage = value; }
    }

    //创建获得记录总数的方法
    public int RecordCount()
    {
        try
        {
            cnn.Open();
            SqlCommand sqlcmd = new SqlCommand(cmd, cnn);
            SqlDataReader sr = sqlcmd.ExecuteReader();//将 CommandText 发送到 Connection 并生成一个 SqlDataReader。
            if (sr.Read())//使 SqlDataReader 前进到下一条记录。SqlDataReader 的默认位置在第一条记录的前面。读取到最后一条记录的后面返回false.
            {
                recordcount = int.Parse(sr["count"].ToString());
                sr.Close();
                return recordcount;
            }
            else
            {
                recordcount = 0;
                return recordcount;
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            cnn.Close();
        }
    }

    //创建获得页数的方法
    public int PageCount()
    {
        try
        {
            if (recordcount % pagesize == 0)
            {
                pagecount = recordcount / pagesize;
                return pagecount;
            }
            else
            {
                pagecount = recordcount / pagesize + 1;
                return pagecount;
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    //绑定数据
    public void databind(DataList dl, LinkButton lbprev, LinkButton lbnext, Label lb)
    {
        try
        {
            cnn.Open();
            SqlDataAdapter da = new SqlDataAdapter(sql, cnn);
            DataSet ds = new DataSet();
            int startindex = pagesize * currentpage;//每页的第一条记录的索引
            da.Fill(ds, startindex, pagesize, "tbnews");
            //DataAdapter的Fill方法的重载形式,即将从da的startinde索引位置开始的pagesize条记录添加到内存ds名为 "tbNews"的表中。
            dl.DataSource = ds.Tables[0].DefaultView;//相当于dl.DataSource = ds.Tables["tbnews"].DefaultView;
            dl.DataKeyField = "id";
            dl.DataBind();
            lbprev.Enabled = true;
            lbnext.Enabled = true;
            if (currentpage == 0)
            {
                lbprev.Enabled = false;
            }
            if (currentpage == pagecount - 1)
            {
                lbnext.Enabled = false;
            }
            int page = currentpage + 1;//返回当前页号,因为页是基于索引0的,所以要加1,才符合一般的习惯
            lb.Text = page.ToString() + " of " + pagecount.ToString();
        }
        catch (Exception ex)
        { throw new Exception(ex.Message); }
        finally
        { cnn.Close(); }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值