开发者

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index in C# asp.Net

开发者 https://www.devze.com 2023-01-15 23:37 出处:网络
I am implementing Grid View in my application...When i try to delete a record from the Grid View it throws this error:

I am implementing Grid View in my application...When i try to delete a record from the Grid View it throws this error:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

This is my Server side 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();

        }

    }
}

My Client Side Grid :

  <asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="False"     AllowSorting="True" onrowdele开发者_如何学Goting="gridview1_RowDeleting" SelectedIndex="1">
  <Columns>
  <asp:TemplateField HeaderText="Delete All">
  <ItemTemplate>
    <asp:CheckBox ID="deleteall" runat="server" />
   </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="Register Number">
    <EditItemTemplate>
    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("RegNo")              %>'></asp:TextBox>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:Label ID="Label2" runat="server" Text='<%# Bind("RegNo") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Section">
    <EditItemTemplate>
        <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Section") %>'></asp:TextBox>
    </EditItemTemplate>
    <ItemTemplate>
        <asp:Label ID="Label3" runat="server" Text='<%# Bind("Section") %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>
 <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" />
    </Columns>
   </asp:GridView>

Can any one pls help me sove this problem by providing some ideas or sample code...


The datakeys collection itself may not be null, but it can contain zero elements. In this example, your grid doesn't set the DataKeyNames property, so this grid isn't tracking any datakeys (the collection will be empty). That is probably why you are getting an index error.

You should set the DataKeyNames property. In your code you also need to check to make sure the collection contains elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消