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 a t 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.
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();
}
}
}
I am new to stackoverflow so I am sorry if this is too much or too little info.
EDIT:
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.
My guess is that your problem is happening in the btnDeleteVideo_Click method because you are changing a data structure (GridView2.Rows) inside a for loop while referencing it in the for loop. This in most languages is bad practice. My advice is first make a list of all the checked rows in your for loop and then do a single delete of multiple rows in one shot rather than doing a delete for each row.