使用IQueryable的ASP.NET GridView分页

时间:2010-09-09 10:03:23

标签: asp.net gridview

我目前正在使用IPagedList来有效地分页我的数据。

使用GridView时,我可以在GridView.PageIndexChanging事件中设置页面索引并重新绑定网格。

问题是,GridView.PageCount属性是只读的,所以默认的寻呼机只显示1页。

我想我将不得不推出自己的GridView实现来解决这个问题?有人有他们已经做过的吗?

2 个答案:

答案 0 :(得分:6)

this post帮助我创建了自己的自定义GridView控件,允许我覆盖寻呼机的初始化并设置记录计数。

public class CustomGridView : GridView
{
    private const string _virtualItemCount = "virtualItemCount";
    private const string _currentPageIndex = "currentPageIndex";

    [Browsable(true), Category("Custom")]
    [Description("Set the virtual item count for this grid")]
    public int VirtualItemCount {
        get
        {
            if (ViewState[_virtualItemCount] == null)
                ViewState[_virtualItemCount] = -1;
            return Convert.ToInt32(ViewState[_virtualItemCount]);
        }
        set
        {
            ViewState[_virtualItemCount] = value;
        }
    }

    private int CurrentPageIndex
    {
        get
        {
            if (ViewState[_currentPageIndex] == null)
                ViewState[_currentPageIndex] = 0;
            return Convert.ToInt32(ViewState[_currentPageIndex]);
        }
        set
        {
            ViewState[_currentPageIndex] = value;
        }
    }

    public override object DataSource
    {
        get
        {
            return base.DataSource;
        }
        set
        {
            base.DataSource = value;
            this.CurrentPageIndex = this.PageIndex;
        }
    }

    protected override void InitializePager(GridViewRow row, int columnSpan, PagedDataSource pagedDataSource)
    {
        if (CustomPaging)
        {
            pagedDataSource.VirtualCount = this.VirtualItemCount;
            pagedDataSource.CurrentPageIndex = this.CurrentPageIndex;
        }
        base.InitializePager(row, columnSpan, pagedDataSource);
    }

    public bool CustomPaging {
        get { return (this.VirtualItemCount != -1); }
    }
}

然后在CustomGridView.PageIndexChanging事件中,我们设置页面索引并重新加载我们的数据(将页面索引和页面大小传递给我们的存储库方法):

    protected void gvAccounts_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvAccounts.PageIndex = e.NewPageIndex;
        BindGrid(e.NewPageIndex, gvAccounts.PageSize);
    }


    protected void BindGrid(int pageIndex, int pageSize)
    {
        var accounts = AccountManager.GetAllAccounts<int>(pageIndex, pageSize, x=> x.AccountId);
        gvAccounts.VirtualItemCount = accounts.TotalCount;
        gvAccounts.DataSource = accounts;
        gvAccounts.DataBind();
    }

希望这有帮助。

答案 1 :(得分:1)

这是我在绑定到IQueryable时使用gridview完成分页和排序的过程:http://bradoyler.com/post/399042473/using-the-asp-net-gridview-with-objectdatasource-and

希望也有帮助!