ASP.NET中的真假分頁

來源:互聯網
上載者:User

        當資料庫中的資料較多的時,以往的DataGrid往往顯得無力,這時就輪到分頁大顯身手,分頁是指將資料庫中的資料分成若干個頁面,獨立顯示出來。我們往往把分頁分為兩種:真分頁和假分頁。

        假分頁說的是先從資料庫中把所有的資料取出來,然後再分頁顯示給使用者。

        1、假分頁前台介面。

        

        2、將AllowPaging屬性設定為True,即允許分頁;設定PageSize,即每頁顯示多少條資料。

        3、運行介面:

        

        再說真分頁,過程如下:

        1、從網站擷取AspNetPager.dll。

        2、添加該組件到工具箱,詳見我的部落格《添加web控制項》。

        3、添加控制項到前台頁面。

        

        4、後台代碼:

    protected void Page_Load(object sender, EventArgs e)        {                 aspPage.RecordCount = 100;        }        /// <summary>        /// 當改變頁數時執行的事件        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>    protected void asp_PageChanged(object sender, EventArgs e)    {            Response.Write("開始與第" + aspPage.StartRecordIndex + "<br>" + "結束於" + aspPage.EndRecordIndex);//開始和結束資料行            BindData();//綁定DataGrid資料    }        /// <summary>        /// 綁定資料        /// </summary>    private void BindData()    {    //綁定DataGrid資料            dgPage.DataSource = dt();            dgPage.DataBind();    }        /// <summary>        /// 根據當前頁數產生資料集        /// </summary>        /// <returns></returns>    private DataTable dt()    {            int pageStart = aspPage.StartRecordIndex;//擷取當前起始資料行            int pageEnd = aspPage.EndRecordIndex;//擷取當前末尾資料行            SqlConnection conn = new SqlConnection("server=.;database=beidaqingniao;uid=sa;pwd=123456;");//建立資料庫連接            string sqltxt = "select * from page  where id between @start and @end";//定義sql語句            SqlCommand sqlcmd = new  SqlCommand (sqltxt, conn);//建立資料庫命令            SqlParameter[] paras = new SqlParameter[] { new SqlParameter ("@start",pageStart ),new SqlParameter ("@end",pageEnd )};//定義參數數組            sqlcmd.Parameters.AddRange(paras);//添加參數到命令            DataSet ds = new DataSet();//定義dataset            SqlDataAdapter da = new SqlDataAdapter(sqlcmd);//建立資料配接器            try            {                    conn.Open();//開啟串連                    da.Fill(ds);//填充ds資料                    return ds.Tables[0];//返回資料集            }            catch (Exception)            {                    throw new Exception("從資料庫擷取資料失敗!");//出現錯誤提示“"從資料庫擷取資料失敗!"”            }            finally            {                    conn.Close();//關閉串連                    sqlcmd.Dispose();//銷掉命令            }    }

        5、運行介面:

        

        為了調用方便,可以寫成預存程序(摘自牛腩):

 -- =============================================-- Author:牛腩-- Create date: 2009-07-22 12:41-- Description:分頁,用到了ROW_NUMBER()-- =============================================create PROCEDURE [dbo].[proc_ShowPage]@tblName   varchar(255),       -- 表名@strGetFields varchar(1000) = '*', -- 需要返回的列,預設*@strOrder varchar(255)='',      -- 排序的欄位名,必填@strOrderType varchar(10)='ASC', -- 排序的方式,預設ASC@PageSize   int = 10,          -- 頁尺寸,預設10@PageIndex int = 1,           -- 頁碼,預設1@strWhere varchar(1500) = '' -- 查詢條件 (注意: 不要加 where)ASdeclare @strSQL   varchar(5000)if @strWhere !=''set @strWhere=' where '+@strWhereset @strSQL='SELECT * FROM ('+'SELECT ROW_NUMBER() OVER (ORDER BY '+@strOrder+' '+@strOrderType+') AS pos,'+@strGetFields+' '+'FROM '+@tblName+' '+@strWhere+') AS sp WHERE pos BETWEEN '+str((@PageIndex-1)*@PageSize+1)+' AND '+str(@PageIndex*@PageSize)exec (@strSQL)

        真假分頁比較。假分頁的優勢在於代碼簡單,如果設定好屬性甚至不用編寫方法即可實現,適合於較少的資料行(幾百);真分頁的優勢在於無論多少資料,取出一頁的時間基本相同,適用於資料龐大的情況(例如百度搜尋結果)。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.