首页  >  文章  >  后端开发  >  C#构建分页应用的实例方法分析

C#构建分页应用的实例方法分析

黄舟
黄舟原创
2017-03-25 13:13:041522浏览

这篇文章主要介绍了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 &#39;%{0}%&#39;", 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;

以上是C#构建分页应用的实例方法分析的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn