Tuesday 13 April 2010

The GridView 'grdNameHere' fired event PageIndexChanging which wasn't handled.


If you've used a GridView on an ASP.NET page and enabled paging, then you will probably be presented with this error message. The fix is simple, but why it does this without some sort of warning from the IDE is rather strange...

So... you have your grid view with paging enabled...

<asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="False" ShowHeader="True" AllowPaging="True" UseAccessibleHeader="True">
 
...column definitions here...
 
</asp:GridView>


We need to override the 'PageIndexChanging' event now, and add some custom code to cater for our paging.


<asp:GridView ID="grdTest" runat="server" AutoGenerateColumns="False" ShowHeader="True" AllowPaging="True" UseAccessibleHeader="True" OnPageIndexChanging="grdTest_PageIndexChanging">
 
...column definitions here...
 
</asp:GridView>


code behind...
/// <summary>
/// Handle page changing on the grid.
/// </summary>
/// <param name="sender">This parameter is not used.</param>
/// <param name="e">This parameter is not used.</param>
protected void grdTest_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
     // Update applications
     this.DataBindingMethod();  // Change this to yours!!
 
     this.grdTest.PageIndex = e.NewPageIndex;
     this.grdTest.DataBind();
}



Note: This data bind method (DataBindingMethod() in this case) must be where your grid is initially bound to.

No comments: