ASP.NET預存程序自訂分頁詳解

來源:互聯網
上載者:User
大家都知道asp.net中的Gridview。datalist等都可以自訂分頁,但是當你翻頁的時候,資料表中的所有資料都會載入到記憶體,重新綁定,當然要是資料量小的話,這是可以的,我們也很樂意用,原因簡單因為方便,但是要是資料量是999999999999……,在資訊爆炸的這個時代海量資料是經常的時,那麼這些控制項內建的分頁就顯得有些……
解決這個問題辦法就是自己動手……不多廢話了,看代碼:
1.首先我是用預存程序來解決的,要弄懂這個問題,首先要從預存程序下手,代碼如下:

CREATE proc getdataset
@TableList Varchar(200)='*',--搜尋表的欄位,比如:’id,datatime,job‘,用逗號隔開
@TableName Varchar(30), --搜尋的表名
@SelectWhere Varchar(500)='',--搜尋條件,這裡不用寫where,比如:job=’teacher‘and class='2'
@SelectOrderId Varchar(20),--表主鍵欄位名。比如:id
@SelectOrder Varchar(200)='', --排序,可以使用多欄位排序但主鍵欄位必需在最前面.也可以不寫,比如:order by class asc
@intPageNo int=1, --頁號
@intPageSize int=10 ,--每頁顯示數
@RecordCount int OUTPUT  --總記錄數(預存程序輸出參數)
as  
   
declare @TmpSelect      NVarchar(600)  
declare @Tmp     NVarchar(600)  

set nocount on--關閉計數

set @TmpSelect = 'select @RecordCount = count(*) from '+@TableName+' '+@SelectWhere

execute sp_executesql
@TmpSelect,    --執行上面的sql語句
N'@RecordCount int OUTPUT' ,   --執行輸出資料的sql語句,output出總記錄數
@RecordCount  OUTPUT

  if (@RecordCount = 0)    --如果沒有貼子,則返回零
       return 0
      
   /*判斷頁數是否正確*/
  if (@intPageNo - 1) * @intPageSize > @RecordCount   --頁號大於總頁數,返回錯誤
     return (-1)
set nocount off--開啟計數
if @SelectWhere != ''
begin
set @TmpSelect = 'select top '+str(@intPageSize)+' '+@TableList+' from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectWhere +' '+@SelectOrder+') and '+@SelectWhere +' '+@SelectOrder
end
else
begin
set @TmpSelect = 'select top '+str(@intPageSize)+' '+@TableList+' from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectOrder+') '+@SelectOrder
end
execute sp_executesql @TmpSelect
return(@@rowcount)
GO

其實代碼也很簡單,學編程的人基本上都是懂資料庫的,這個預存程序估計不是問題。
其他的代碼我都做瞭解釋,有顏色的那段我沒有解釋,我在這裡解釋一下。其實也很簡單,大家來看:
select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectWhere +' '+@SelectOrder+'
這段代碼的執行結果是什麼了,是不是當前頁前面的主鍵的集合啊,現在我們從所有的表中選出主鍵的值不在這個結果的之內的pagesize個記錄不就是當前頁的內容了嗎?
2.aspx頁面就不用再將了吧?我這裡將代碼寫上:

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

<!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">
    <>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="180px" Width="867px">
            <Columns>
                <asp:BoundField DataField="job_id" HeaderText="job_id" />
                <asp:BoundField DataField="job_desc" HeaderText="job_desc" />
                <asp:BoundField DataField="max_lvl" HeaderText="max_lxl" />
            </Columns>
        </asp:GridView>
   
    </>
           <asp:HyperLink ID="hylfirst" runat="server">首頁</asp:HyperLink>
         
        <asp:HyperLink ID="hylprev" runat="server">上一頁</asp:HyperLink>
         
        <asp:HyperLink ID="hylnext" runat="server">下一頁</asp:HyperLink>
        <asp:HyperLink ID="hylend" runat="server">尾頁</asp:HyperLink>
               第<asp:Label ID="lbRow" runat="server" Text="Label"></asp:Label>頁,
          共<asp:Label ID="lbpage" runat="server" Text="Label"></asp:Label>頁,共<asp:Label
            ID="lbRecord" runat="server" Text="Label"></asp:Label>條記錄,轉到<asp:TextBox ID="txtlink"
                runat="server" Width="29px"></asp:TextBox>
        頁<asp:LinkButton ID="link" runat="server" OnClick="link_Click" TabIndex="1">轉到</asp:LinkButton>
    </form>
</body>
</html>

3.cs頁面其實也每頁什麼好講的,也就是一些常用的代碼罷了……我把代碼加上,大家看看,要是有疑問的可以回複我再解釋:

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 _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        this.bind();
        
    }

    protected void link_Click(object sender, EventArgs e)
    {
        int page = Convert.ToInt32(txtlink.Text);
        Response.Redirect("aa.aspx?CurrentPage="+page+"");
    }
    public void bind()
    {
        int sumPage;
        int pageNo = 1;
        int pageSize = 3;
        if (Request.QueryString["CurrentPage"] == null)
        {
            pageNo = 1;
        }
        else
        {
            pageNo = Int32.Parse(Request.QueryString["CurrentPage"]);
        }

        SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["ConStr"]);
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = new SqlCommand();
        da.SelectCommand.Connection = conn;
        da.SelectCommand.CommandText = "getdataset";
        da.SelectCommand.CommandType = CommandType.StoredProcedure;
        da.SelectCommand.Parameters.Add("@TableList", SqlDbType.VarChar, 200).Value = "job_id,job_desc,max_lvl";
        da.SelectCommand.Parameters.Add("@TableName", SqlDbType.VarChar, 30).Value = "jobs";
        //da.SelectCommand.Parameters.Add("@SelectWhere", SqlDbType.VarChar, 500).Value = "where d=1";
        da.SelectCommand.Parameters.Add("@SelectOrderId", SqlDbType.VarChar, 20).Value = "job_id";
        da.SelectCommand.Parameters.Add("@SelectOrder", SqlDbType.VarChar, 200).Value = "order by min_lvl asc";
        da.SelectCommand.Parameters.Add("@intPageNo", SqlDbType.Int).Value = pageNo;
        da.SelectCommand.Parameters.Add("@intPageSize", SqlDbType.Int).Value = pageSize;
        da.SelectCommand.Parameters.Add("@RecordCount", SqlDbType.Int).Direction = ParameterDirection.Output;
        da.SelectCommand.Parameters.Add("RowCount", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
        DataSet ds = new DataSet();
        da.Fill(ds, "jobs");
        GridView1.DataSource = ds;
        GridView1.DataBind();
        Int32 RecordCount = (Int32)da.SelectCommand.Parameters["@RecordCount"].Value; //求出總記錄數,該值是output出來的值
        Int32 RowCount = (Int32)da.SelectCommand.Parameters["RowCount"].Value;         //求出當前頁中的記錄數,在最後一頁不等於pagesize,
        lbRecord.Text = RecordCount.ToString();
        lbRow.Text = pageNo.ToString();
        sumPage = (Int32)RecordCount / pageSize;
        if (RecordCount % pageSize > 0)
        {
            sumPage = sumPage + 1;
        }
        lbpage.Text = sumPage.ToString();
        if (pageNo > 1)
        {
            hylfirst.NavigateUrl = "aa.aspx?CurrentPage=1";
            hylprev.NavigateUrl = string.Concat("aa.aspx?CurrentPage=", "", pageNo - 1);
        }
        else
        {
            hylprev.NavigateUrl = "";
            hylfirst.NavigateUrl = "";
            hylfirst.Visible = false;
            hylprev.Visible = false;
        }
        if (pageNo < sumPage)
        {
            hylend.NavigateUrl = string.Concat("aa.aspx?CurrentPage=", "", sumPage);
            hylnext.NavigateUrl = string.Concat("aa.aspx?CurrentPage=", "", pageNo + 1);
        }
        else
        {
            hylnext.NavigateUrl = "";
            hylend.NavigateUrl = "";
            hylend.Visible = false;
            hylnext.Visible = false;
        }

    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.