我使用的是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