title: GridView Page Index
body: <p>I'm using a GridView to show data from a database and i am having a problem with PageIndex, the pagination is working correctly i can see all the information but I have a problem with a button placed at the end of each row wich action is delete a row</p>
  
  <p>In the Grid View the button works absolutely fine in the first page the action of deleting the row works fine but when i change to the second page</p>
  
  <pre><code>Exception thrown: 'System.ArgumentOutOfRangeException' in mscorlib.dll ("Index was out of range. Must be non-negative and less than the size of the collection.")
  </code></pre>
  
  <p>The problem is that the Page Size for my GridView is set to 10, so in the first page the rows are set (obviously like an array) from 0 to 9 but when i change to the second page the array continues from 10 to 19, so if I click the button on the first row of the second page the CommandArgument returns "10" </p>
  
  <p><a href="https://i.stack.imgur.com/8BbrZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8BbrZ.png" alt="debug result of command argument"></a></p>
  
  <p>(wich translates to the 11 element on an array) and it's bigger than the page size of the gridview</p>
  
  <pre><code>protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
      {
          GridView1.PageIndex = e.NewPageIndex;
          FillGrid();
      }
  
  public void FillGrid()
      {
          Methods metodos = new Methods();
          string query = "SELECT * FROM ul";
          GridView1.DataSource = metodos.Query(query);
          GridView1.DataBind();
      }
  </code></pre>
  
  <p>The error happens here</p>
  
  <pre><code>if (e.CommandName == "btnDelete")
          {   
              int index = Convert.ToInt32(e.CommandArgument);
              //Get row number
              GridViewRow row = GridView1.Rows[index];
          }
  </code></pre>
  
  <p>The variable index returns 10 and the error occurs because that value (11 element in the array) is bigger than the page size of the grid and it's not "finding" the row like the error says <code>less than the size of the collection</code></p>
  
  <p>I have tried setting the GridView1.PageIndex = 0; but the pagination stops working, if place the databind after setting the GridView1.PageIndex = e.NewPageIndex; the pagination stops working again</p>
  
  <p>EDIT: This is the button on the gridview</p>
  
  <pre><code>&lt;asp:Button runat="server" Text="Delete CommandName="btnDelete" CommandArgument="&lt;%# Container.DataItemIndex %&gt;" CausesValidation="false"/&gt;
  </code></pre>