分页方法:
public void BindBoundControl<TSource>(IEnumerable<TSource> DataSource, GridView BoundControl, int PageSize,int PageIndex)
{
//获取总记录数(这里可以使用参数传入总页数 就不必每次都执行下面方法)
int totalRecordCount = DataSource.Count();
//计算总页数
int totalPageCount = 0;
if (PageSize == 0)
{
PageSize = totalRecordCount;
}
if (totalRecordCount % PageSize == 0)
{
totalPageCount = totalRecordCount / PageSize;
}
else
{
totalPageCount = totalRecordCount / PageSize + 1;
}
//从参数中获取当前页码
int CurrentPageIndex = PageIndex;
//如果从网址参数中获取页码不正确 设置页码为第一页
//if (!int.TryParse(HttpContext.Current.Request.QueryString["Page"], out CurrentPageIndex) || CurrentPageIndex <= 0 || CurrentPageIndex > totalPageCount)
//{
// CurrentPageIndex = 1;
//}
if (CurrentPageIndex <= 0 || CurrentPageIndex > totalPageCount)
{
CurrentPageIndex = 1;
}
//绑定数据源
BoundControl.DataSource = DataSource.Skip((CurrentPageIndex - 1) * PageSize).Take(PageSize);
BoundControl.DataBind();
}
重载:
public void BindBoundControl<TSource>(IEnumerable<TSource> DataSource, TSource type, GridView BoundControl, int PageSize, int PageIndex)
{
this.BindBoundControl(DataSource, BoundControl, PageSize,PageIndex);
}
调用:
private void BindEmployees(int index)
{
Table<Employees> localDataTable;
localDataTable = objCategories.selectEmployees();
var list = (from em in localDataTable
orderby em.EmployeeID descending
select new
{
EmployeeID = em.EmployeeID,
LastName = em.LastName,
FirstName = em.FirstName,
Title = em.Title,
TitleOfCourtesy = em.TitleOfCourtesy
});
BindBoundControl(list, this.GridView1, 5, index);
}