概述
C#通用分页
- 代码
代码
// An highlighted block
/// <summary>
/// 获取分页数据
/// </summary>
/// <param name="Constring">数据库连接字符串</param>
/// <param name="SqlData">要查询的语句</param>
/// <param name="sqlwhere">语句条件</param>
/// <param name="orderBy">排序字段</param>
/// <param name="pageIndex">当前页码</param>
/// <param name="pageSize">一页多少条</param>
/// <returns></returns>
public DataTable GetPaginData(string Constring, string SqlData, string sqlwhere, string orderBy, int pageIndex, int pageSize)
{
string sqlFormat = @"select *
from (select *,COUNT(1) OVER() AS TotalCount,ROW_NUMBER() over (order by {2}) AS RowNumber
from {0}
where 1 = 1 {1}) T
where RowNumber between @skip and @end
order by {2}";
if (!string.IsNullOrEmpty(sqlwhere))
{
sqlwhere = "and " + sqlwhere;
//如果where语句后面有and就去除最后一个
sqlwhere = sqlwhere.Remove(sqlwhere.LastIndexOf("a"),3);
}
string Sqlstring = string.Format(sqlFormat, SqlData, sqlwhere, orderBy);
int skip = (pageIndex - 1) * pageSize + 1;
int end = pageIndex * pageSize;
SqlParameter[] Parameters = new SqlParameter[]
{
new SqlParameter("@skip", skip),
new SqlParameter("@end", end)
};
return GetPagingTable(Constring, Sqlstring, Parameters);
}
/// <summary>
/// 执行sql,返回datatable
/// </summary>
/// <param name="Constring">数据库连接字符串</param>
/// <param name="Sqlstring">要执行的Sql</param>
/// <param name="Parameters">参数</param>
/// <returns></returns>
private DataTable GetPagingTable(string Constring, string Sqlstring, SqlParameter[] Parameters)
{
using (SqlConnection SqlCon = new SqlConnection(Constring))
{
using (SqlCommand SqlCom = new SqlCommand(Sqlstring, SqlCon))
{
foreach (SqlParameter s in Parameters)
{
SqlCom.Parameters.Add(s);
}
SqlDataAdapter sda = new SqlDataAdapter(SqlCom);
DataTable datatable = new DataTable();
try
{
sda.Fill(datatable);
return datatable;
}
catch (System.Exception)
{
return datatable;
}
finally
{
sda.Dispose();
}
}
}
}
最后
以上就是动人茉莉为你收集整理的C#通用分页的全部内容,希望文章能够帮你解决C#通用分页所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复