本文实例讲述了C#构建分页应用的方法。分享给大家供大家参考,具体如下:
1、SQL语句
1
2
3
4
|
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、后台方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
/// <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()方法等请自己完善。
一些计算方法
1
2
3
4
5
|
//分页
Int64 startNumber = (param.PageIndex - 1) * param.PageSize + 1;
Int64 endNumber = startNumber + param.PageSize - 1;
//总页数 = (数据总数 + 分页大小 -1) / 分页大小
TotalPage = (TotalCount + PageSize - 1) / PageSize;
|
希望本文所述对大家C#程序设计有所帮助。