這篇文章主要介紹了C#構建分頁應用的方法,結合執行個體形式分析了C#建立分頁功能的具體步驟與相關實現技巧,需要的朋友可以參考下
本文執行個體講述了C#構建分頁應用的方法。分享給大家供大家參考,具體如下:
1、SQL語句
WITH [temptableforStockIC] AS ( SELECT *,ROW_NUMBER() OVER (ORDER BY CreateTime DESC) AS RowNumber FROM [StockIC] WHERE 1=1 AND Model = 'FTY765OP')SELECT * FROM [temptableforStockIC] WHERE RowNumber BETWEEN 1 AND 10
2、後台方法
/// <summary>/// 表名/// </summary>private const string _tableNane = "StockIC";/// <summary>/// 擷取庫存列表/// </summary>public List<StockIcResult> GetStockIcList(StockIcParam param){ List<StockIcResult> list = new List<StockIcResult>(); string sql = "WITH [temptablefor{0}] AS"; sql += " (SELECT *,ROW_NUMBER() OVER (ORDER BY {1}) AS RowNumber FROM [{0}] WHERE 1=1 {2})"; sql += " SELECT * FROM [temptablefor{0}] WHERE RowNumber BETWEEN {3} AND {4}"; StringBuilder sqlCondition = new StringBuilder(); List<SqlParameter> sqlParams = new List<SqlParameter>(); //型號 if (!String.IsNullOrEmpty(param.Model)) { sqlCondition.AppendFormat(" AND Model LIKE '%{0}%'", param.Model); } //開始時間 if (param.BeginTime.HasValue) { sqlCondition.Append(" AND CreateTime >= @BeginTime"); sqlParams.Add(new SqlParameter("@BeginTime", param.BeginTime.Value)); } //結束時間 if (param.EndTime.HasValue) { sqlCondition.Append(" AND CreateTime < @EndTime"); sqlParams.Add(new SqlParameter("@EndTime", param.EndTime.Value.AddDays(1))); } //排序 if (String.IsNullOrWhiteSpace(param.OrderBy)) { param.OrderBy = " CreateTime DESC"; } //分頁 param.PageIndex = param.PageIndex - 1; Int64 startNumber = param.PageIndex * param.PageSize + 1; Int64 endNumber = startNumber + param.PageSize - 1; //拼裝SQL sql = String.Format(sql, _tableNane, param.OrderBy, sqlCondition, startNumber, endNumber); //執行SQL語句 DataSet dataSet = DBHelper.GetReader(sql.ToString(), sqlParams.ToArray()); list = TranToList(dataSet); return list;}
注意:DBHelper.GetReader()方法、TranToList()方法等請自己完善。
一些計算方法
//分頁Int64 startNumber = (param.PageIndex - 1) * param.PageSize + 1;Int64 endNumber = startNumber + param.PageSize - 1;//總頁數 = (資料總數 + 分頁大小 -1) / 分頁大小TotalPage = (TotalCount + PageSize - 1) / PageSize;