GridView是asp.net2.0新推出的控件,用来取代DataGrid。对于很多简单操作,的确方便了不少,例如不写一句代码结合sqldatasource实现增删改、翻页等操作。
但在很多细粒度的控制方面,反而不如DataGrid,所以大部分时间,笔者依然采用DataGrid,近日重写GridView控件,研究了一下如果通过GridView实现自定义数据分页,成功解决了这个问题。
GridView分页功能比DataGrid强大了不少,但没有类似dataGrid的VirtualItemCount属性,如何实现自定分页成了难题,翻阅若干资料,终于找到了ObjectDataSource这个对象辅助完成的解决办法,经过改造,成功实现了想要的功能。现把实现思路给大家讲一讲:
定义适配器类
internal class ObjectDataSourceAdapter
{
private object _dt;
private int _vic;
//this is the constructor that takes as parameters a cute little datatable
// with the right 10 records, an an integer vic = virtualitemcount
public ObjectDataSourceAdapter(object dt, int vic)
{
_dt = dt;
_vic = vic;
}
//this returns the datatable (10 records)
public object GetData()
{
return _dt;
}
//this returns the total number of records in the table (30.000)
public int VirtualItemCount()
{
return _vic;
}
//this also returns the datatable (10 records) but the ODS needs it for paging purposes
public object GetData(int startRow, int maxRows)
{
return _dt;
}
}
设置ObjectDataSource为数据源
ObjectDataSource ods = new ObjectDataSource();
ods.ID = "ods" ;
ods.EnablePaging = this.AllowPaging; //the paging of ODS depends on the paging of the GridView
ods.TypeName = "ObjectDataSourceAdapter"; //be sure to prefix the namespace of your application !!! e.g. MyApp.MyTableAdapter
ods.SelectMethod = "GetData";
ods.SelectCountMethod = "VirtualItemCount";
ods.StartRowIndexParameterName = "startRow";
ods.MaximumRowsParameterName = "maxRows";
ods.EnableViewState = false;
ods.ObjectCreating += new ObjectDataSourceObjectEventHandler(ods_ObjectCreating);
this.DataSource = ods;
this.DataBind();
委托方法
private void ods_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
e.ObjectInstance = new ObjectDataSourceAdapter(dt, this.RecordCount);
}
这里的dt就是你的分页数据,支持datatable和datareader RecordCount就是VirtualItemCount