Tuesday, 16 November 2010

GridView fires a RowCommand event when the paging is triggered?

Yes, very odd behaviour this one.
I guess the assumption is that RowXXXXX events relate to Row events - selection, creation, deletion, editing. But RowCommand actually caters for any button that is clicked on a GridView.
Therefore paging controls are buttons, and therefore fire the RowCommand event with the CommandSource as "Page".
Therefore something like this will always fire both events:

<%@Page Language="C#" AutoEventWireup="true"%>
<script runat="server">
   1:  
   2: protected void Page_Load(object sender, EventArgs e)
   3: {
   4:      if(!IsPostBack)
   5:      {
   6:          ArrayList list = new ArrayList();
   7:          list.Add ( "Item1" );
   8:          list.Add ( "Item2" );
   9:          list.Add ( "Item3" );
  10:          list.Add ( "Item4" );
  11:     
  12:          this.GridView1.DataSource = list;
  13:          this.GridView1.DataBind();
  14:      }
  15: }
  16:  
  17: protected void RowCom( object sender, GridViewRowCommandArgs e)
  18: {
  19:      Page.Controls.Add ( new Label("Row_Command fired => CommandSource = " + e.CommandSource) );
  20: }
  21:  
  22: protected void Row_Index( object sender, GridViewPageIndexChangedCommandArgs e)
  23: {
  24:      Page.Controls.Add ( new Label("PageIndexChanged fired") );
  25: }
</script> <asp:GridView runat="server" ID="GridView1" OnRowCommand="RowCom" OnPageIndexChanging="Row_Index" EnablePaging="true" PageSize="2"> </asp:GridView>
Therefore, you have to ensure that in the RowCommand, that you only filter the events which you want, rather than assuming only row clicks will come through this event.