I am working on a site that users can add and delete videos from a list.
All the adding and removing is done with checkboxes. I can add multiple videos at a time but when I try to delete more than one of them at a time from the list, it gives me this error:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
However when there are no issues removing one at a time. Also when I get the error and go back the checked videos are gone.
This is in C# ASP.NET and I am not sure where the error is, but I believe it to be in the btnDeleteVideo_Click event. I am showing the other event (btnAddVideo_Click) as reference if needed. I can remove that if it would help. I am new to stackoverflow so I am sorry if this is too much or too little info.
Here is the code for both the adding and removing events:
protected void btnAddVideo_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in GridView3.Rows)
{
CheckBox chkItem = (CheckBox)gvr.FindControl("cbAdd");
if (chkItem.Checked)
{
String sRecID = GridView3.DataKeys[gvr.RowIndex].Value.ToString();
Session["videorecid"] = sRecID;
SqlDataSource2.Insert();
SqlDataSource2.SelectCommand = "SELECT * FROM dealervideo inner join videos on videos.RecID = dealervideo.VideoRecID inner join dealers on dealers.RecID = dealervideo.DealerRecID where dealers.RecID = " + hidRecID.Value;
GridView2.DataBind();
}
}
GridView2.DataBind();
}
protected void btnDeleteVideo_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in GridView2.Rows)
{
CheckBox chkItem = (CheckBox)gvr.FindControl("cbDelete");
if (chkItem.Checked)
{
String sRecID = GridView2.DataKeys[gvr.RowIndex].Value.ToString();
Session["videorecid"] = sRecID;
SqlDataSource2.Delete();
SqlDataSource2.SelectCommand = "SELECT * FROM dealervideo inner join videos on videos.RecID = dealervideo.VideoRecID inner join dealers on dealers.RecID = dealervideo.DealerRecID where dealers.RecID = " + hidRecID.Value;
GridView2.DataBind();
}
}
}
The problem is the logic of
btnDeleteVideo_Click.Imagine you have 5 items in your list, numbered 0 to 4, and you try to delete 2 at once.
Your code above now loops through all five rows. When it gets to the first deletion, it removes a row by deleting from the data source and rebinding.
It now continues through the loop until it finds the second item marked from deletion – except that your grid now contains one less row since you deleted and rebound.
So the line
String sRecID = GridView2.DataKeys[gvr.RowIndex].Value.ToString();will have a tendency to explode as the original RowIndex may now be higher than the actual number of rows.A better approach would be to work out all the rows you want to delete by loopin as you are, but only delete and rebind at the end.