ASP.NET DataGrid and custom paging


I'm trying to implement a DataGrid in ASP.NET, and want to achieve custom paging so that I don't have to provide all the data in one go. I've spent several hours researching on the internet, but haven't found anything useful.

When I view the page I see the first set of results in the grid, with the previous link disabled. When I click next however, I once again see the first page of the grid with the previous link disabled. When debugging the code I ascertained that the MyGrid_PageIndexChanged() event handler is never called.

I've included my simplified code below. I've changed variable names and omited methods to focus on the datagrid paging issue.

In the ASPX file:

<asp:DataGrid ID="myGrid" runat="server" GridLines="None" UseAccessibleHeader="true" AutoGenerateColumns="false" AllowPaging="true" AllowCustomPaging="true" PageIndexChanged="MyGrid_PageIndexChanged">
<PagerStyle Mode="NextPrev" NextPageText="Next >" PrevPageText="< Previous" />

<asp:BoundColumn HeaderText="Title" DataField="Name" />
<asp:BoundColumn HeaderText="Date" DataField="Date" />

And in the CS file:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
                            myGrid.PageSize = 20;
                            myGrid.VirtualItemCount = GetNumItems();

    protected void MyGrid_PageIndexChanged(object sender, DataGridPageChangedEventArgs e)
        myGrid.CurrentPageIndex = e.NewPageIndex;

    private int GetNumItems()
        return 500;

    private void BindMyGrid()
            Data[] array = GetDataFromInternetSomehow();
            this.myGrid.DataSource = array;

    private class Data
        public string Date { get; set; }
        public string Name { get; set; }

Any thoughts on this would be much appreciated.

Best Solution

There is an error in your ASPX: to wire up the PageIndexChanged event handler use the property OnPageIndexChanged (not PageIndexChanged as in your code):

<asp:DataGrid ID="myGrid" runat="server"
   OnPageIndexChanged="MyGrid_PageIndexChanged"  /// <--- here's the error

Then, if you have AllowCustomPaging="true", you must ensure that the GetDataFromInternetSomehow() method will only return the data for the currently selected page, e.g. pass the current page to the method and return only the corresponding data:


Otherwise, disable custom paging and it will just work (but all data will be loaded everytime).

Related Question