title: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index in C# asp.Net
body: <p>I am implementing Grid View in my application...When i try to delete a record from the Grid View it throws this error:</p>
  
  <p><strong>Index was out of range. Must be non-negative and less than the size of the collection.
  Parameter name: index</strong></p>
  
  <p>This is my Server side Code:</p>
  
  <pre><code>protected void gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  {
  
      foreach (GridViewRow gv in gridview1.Rows)
      {
          CheckBox check = (CheckBox)gv.FindControl("deleteall");
          if (check.Checked)
          {
              con.Open();
              if (gridview1.DataKeys != null)
              {
     **In this line only the error occurs**
                  int RegNo = Convert.ToInt32(gridview1.DataKeys[gv.RowIndex].Value);
              }
              cmd = new MySqlCommand("delete from studentinfo where Regno='" + 1 + "'", con);
              // cmd.Parameters.Add("@id", RegNo);
              cmd.ExecuteNonQuery();
              con.Close();
  
          }
  
      }
  }
  </code></pre>
  
  <p>My Client Side Grid :</p>
  
  <pre><code>  &lt;asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="False"     AllowSorting="True" onrowdeleting="gridview1_RowDeleting" SelectedIndex="1"&gt;
    &lt;Columns&gt;
    &lt;asp:TemplateField HeaderText="Delete All"&gt;
    &lt;ItemTemplate&gt;
      &lt;asp:CheckBox ID="deleteall" runat="server" /&gt;
     &lt;/ItemTemplate&gt;
    &lt;/asp:TemplateField&gt;
    &lt;asp:TemplateField HeaderText="Register Number"&gt;
      &lt;EditItemTemplate&gt;
      &lt;asp:TextBox ID="TextBox2" runat="server" Text='&lt;%# Bind("RegNo")              %&gt;'&gt;&lt;/asp:TextBox&gt;
      &lt;/EditItemTemplate&gt;
      &lt;ItemTemplate&gt;
          &lt;asp:Label ID="Label2" runat="server" Text='&lt;%# Bind("RegNo") %&gt;'&gt;&lt;/asp:Label&gt;
      &lt;/ItemTemplate&gt;
  &lt;/asp:TemplateField&gt;
  &lt;asp:TemplateField HeaderText="Section"&gt;
      &lt;EditItemTemplate&gt;
          &lt;asp:TextBox ID="TextBox3" runat="server" Text='&lt;%# Bind("Section") %&gt;'&gt;&lt;/asp:TextBox&gt;
      &lt;/EditItemTemplate&gt;
      &lt;ItemTemplate&gt;
          &lt;asp:Label ID="Label3" runat="server" Text='&lt;%# Bind("Section") %&gt;'&gt;&lt;/asp:Label&gt;
      &lt;/ItemTemplate&gt;
  &lt;/asp:TemplateField&gt;
   &lt;asp:CommandField HeaderText="Delete" ShowDeleteButton="True" /&gt;
      &lt;/Columns&gt;
     &lt;/asp:GridView&gt;
  </code></pre>
  
  <p>Can any one pls help me sove this problem by providing some ideas or sample code...</p>