在自己的項目中有一個文章的管理頁面需要用到分頁,
這種分頁方法是在黑馬的一個視頻中看到的,便用在了自己的項目中。
但是使用控件實在是太丑,雖然我寫的也丑......。
gridview 控件提供的分頁已經足夠強大,微小的數據量根本不需要在意。
而本文所介紹的分頁一樣無法應對大量的數據,只是一種簡單的實現。
通過傳入的 請求頁碼 以及程序設定好的 每頁顯示的數量 ,計算出一頁數據的開始數與結束數,調用 GetPageList 方法,返回泛型數據集合。
1 //pageindex:頁碼,paesize:每頁數量 2 3 4 public static List<ArticleBLL> GetArticleMenu(int pageindex, int pagesize) 5 { 6 int start = (pageindex - 1) * pagesize + 1; 7 int end = pagesize * pageindex; 8 List<ArticleBLL> list = GetPageList(start, end); 9 return list; 10 }
GetPageList 方法,接收到上面方法的計算結果,查詢數據然后返回。
1 // 傳入 開始id 以及 結束id 獲得數據列表 2 3 4 private static List<ArticleBLL> GetPageList(int start, int end) 5 { 6 string sqlstring = "select * from (select row_number() over(order by Time desc) as num,* from Article)as t where t.num >= @start and t.num <= @end"; 7 SqlParameter[] para = { 8 new SqlParameter ("@start",start), 9 new SqlParameter("@end",end) 10 }; 11 DBHelp db = new DBHelp(); 12 DataTable dt = db.GetDataTable(sqlstring, para); 13 List<ArticleBLL> list = null; 14 if (dt.Rows.Count > 0) 15 { 16 list = new List<ArticleBLL>(); 17 ArticleBLL article = null; 18 foreach (DataRow row in dt.Rows) 19 { 20 article = new ArticleBLL(); 21 LoadEnity(row, article); 22 list.Add(article); 23 } 24 } 25 return list; 26 }
轉化數據。
1 //轉化數據 2 private static void LoadEnity(DataRow row, ArticleBLL article) 3 { 4 article.ID = Convert.ToInt32(row["ID"]); 5 article.Title = Convert.ToString(row["Title"]); 6 article.Text = Convert.ToString(row["Text"]); 7 article.Time = Convert.ToDateTime(row["Time"]); 8 }
生成頁碼條
我使用的前端框架是 Bootstrap v2 在這里直接將樣式寫在輸出里了。
1 //產生數字頁碼條 2 //頁面產生10個數字頁碼 3 //pageindex 傳來的請求頁碼值 4 //articlemenucount 總頁碼數量 5 //pagesize 每頁數量值 6 7 8 public static string GetPageBar(int pageindex,int pagesize) 9 { 10 int articlemenucount = GetArticleMenuCount(pagesize); 11 if (articlemenucount == 1) 12 { return string.Empty; } 13 int start = pageindex - 5; 14 if (start < 1) 15 { start = 1; } 16 int end = start + pagesize - 1; 17 if (end > articlemenucount) 18 { end = articlemenucount; } 19 StringBuilder pagebar = new StringBuilder(); 20 pagebar.Append("<div class=\"pagination pagination-right\"><ul>"); 21 for (int i = start; i <= end; i++) 22 { 23 if (i == pageindex) 24 { pagebar.Append("<li class=\"active\"><a>" + i +"</a></li>"); } 25 else 26 { pagebar.Append(string.Format("<li><a href='arctilemenu.aspx?page={0}'>{0}</a></li>",i)); } 27 } 28 pagebar.Append("</ul></div>"); 29 return pagebar.ToString(); 30 }
這兩個方法求出數據的總條數,然后計算全部的頁數。供上面方法計算頁碼條頁碼。
1 //求總頁數 2 3 4 private static int GetArticleMenuCount(int pagesize) 5 { 6 int rowcount = GetRowCount(); 7 int pagecount = Convert.ToInt32(Math.Ceiling((double)rowcount / pagesize)); 8 return pagecount; 9 }
1 //求出總記錄數 2 private static int GetRowCount() 3 { 4 string sqlstring = "select count(*) from Article"; 5 DBHelp db = new DBHelp(); 6 return Convert.ToInt32(db.GetInt(sqlstring)); 7 }
在調用時只需要傳入每頁的數據條數以及當前請求的頁碼就可以了。
最后,真的是好丑啊。