DataTable对象翻页功能 DataTablePagination


项目一直都是用的存储过程分页的

今天做了一个功能  用到了翻页  但是代码都是一模一样的 用到此功能上 翻页就是异常  每次翻页对象都是乱套的

调试查看数据库返回结果都是正确的数据  翻页功能还是封装编译了 无奈之下  自己编写此DataTable对象的翻页功能

能用存储过程分页的 一定要用存储过程 因为DataTable分页是要把数据全部从数据库读取出来再进行处理的 太消耗资源 得不偿失

 

代码入下

 

// ===================================================================
// 创建时间:2012年2月22日, PM 02:53:02
// 描述:DataTable翻页功能
// ===================================================================

using System.Data;
namespace Pagination
{
public static class DataTablePagination
{

 

     /// <summary>
     /// DataTable翻页功能
     /// </summary>
     /// <param name="dt">数据源</param>
     /// <param name="PageIndex">当前页</param>
     /// <param name="PageSize">每页显示多少条数据</param>
     /// <returns>返回处理后的数据</returns>
public static DataTable GetDataTablePagination(this DataTable dt, int PageIndex, int PageSize)
{
//如果不是有效参数 返回null
if (dt == null || dt.Rows.Count == 0 || PageSize <= 0 || PageIndex < 0)
{
return null;
}
//如果总数小于分页数直接返回数据
if (dt.Rows.Count <= PageSize)
{
return dt;
}
int _totalCount = 0;
_totalCount = dt.Rows.Count / PageSize;
if (dt.Rows.Count % PageSize > 0)
{
_totalCount++;
}
PageIndex++;
for (int i = 1; i < PageIndex; i++)
{
dt = RemoveDataTableRows(dt, 0, PageSize);
}
return GetDataTableRows(dt, 0, PageSize);
}
/// <summary>
/// 根据数据表 指定 行数的索引值 删除指定的行个数
/// </summary>
/// <param name="dt">要操作的数据表</param>
/// <param name="rowIndex">开始删除的行号(行索引值)</param>
/// <param name="num">删除行数</param>
/// <returns>返回处理后的数据表</returns>
public static DataTable RemoveDataTableRows(DataTable dt, int rowIndex, int num)
{
if (dt == null || dt.Rows.Count == 0 || rowIndex < 0 || num < 0)
{
return dt;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i == rowIndex)
{
for (int j = 0; j < num; j++)
{
dt.Rows.RemoveAt(rowIndex);//.Rows[].Delete();
}
break;
}
}
return dt;
}
/// <summary>
/// 根据数据表 指定 行数的索引值 获取指定的行个数数据
/// </summary>
/// <param name="dt">要操作的数据表</param>
/// <param name="rowIndex">开始获取数据的行号(行索引值)</param>
/// <param name="num">获取的行数</param>
/// <returns>返回处理后的数据表</returns>
public static DataTable GetDataTableRows(DataTable dt, int rowIndex, int num)
{
if (dt == null || dt.Rows.Count == 0 || rowIndex < 0 || num < 0)
{
return dt;
}
DataTable dt1 = new DataTable();
dt1 = dt.Clone();
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i == rowIndex)
{
       for (int j = 0; j < num; j++)                    

{                        

if (i + j + 1 <= dt.Rows.Count)                        

{                            

dt1.Rows.Add(dt.Rows[rowIndex + j].ItemArray);                        

}                    

}                    

break;

}
}
return dt1;
}
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM