我使用的是ASP.net,我在gridview上添加了一个删除按钮,并试图删除点击按钮的行。事情是,虽然,我得到一个InvalidOperationException我的foreach。ASP.net GridView InvalidOperationException foreach删除时
我可能在代码中有其他错误,或者我的逻辑可能是错误的,所以如果你看到任何它,请将它们指出来。谢谢。
的GridView cart.ASPX:
<asp:GridView ID="CartGrid" runat="server" AutoGenerateColumns="false" OnRowDeleting="RemoveSelected">
<Columns>
<asp:BoundField DataField="product_name" HeaderText="Name" />
<asp:BoundField DataField="price_per_unit" HeaderText="Price" />
<asp:BoundField DataField="unit" HeaderText="Unit" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="delSelected" runat="server" Text="Delete" CommandName="Delete"></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
删除方法cart.ASPX.CS
protected void RemoveBtn(object sender, GridViewDeleteEventArgs e)
{
ArrayList cartList = (ArrayList)Session["cartList"];
GridViewRow row = (GridViewRow)CartGrid.Rows[e.RowIndex];
String name = row.Cells[0].Text;
//String name = (string)CartGrid.DataKeys[e.RowIndex].Value;
//String name = CartGrid.SelectedRow.Cells[1].Text;
foreach (product p in cartList)
{
if (p.product_name.Equals(name))
{
cartList.Remove(p);
}
}
CartGrid.DataBind();
}
你不能修改迭代变量,而是修改你正在迭代的集合。 – C4u
可能重复[有效地从'foreach'内删除项目](http://stackoverflow.com/questions/8791557/efficiently-deleting-item-from-within-foreach) – klashar
可能重复的[为什么我不能修改循环变量在foreach?](http://stackoverflow.com/questions/3551696/why-cant-i-modify-the-loop-variable-in-a-foreach) – C4u