我使用的是ASP.net,我在一个网格视图上添加了一个删除按钮,而我正在尝试删除被点击的按钮所在的行。不过,问题是,我的前额会得到一个InvalidOperationException。
我可能在代码中有其他错误,或者我的逻辑可能是错误的,所以如果你看到了任何错误,请指出它们。谢谢。
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>delete方法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();
}发布于 2017-02-27 21:00:10
您不能使用foreach修改您正在迭代的集合-请参阅this question了解更多信息。
发布于 2017-02-27 21:02:19
嗨,我认为问题是你正在使用cartlist for循环,同时你想从同一个循环中删除值,这是不可能的。
你只需要改变你的方法,比如创建一个空列表,然后将所有的索引添加到这个列表中,这样你就必须从下往上删除所有的值,这样它就不会通过删除的值来影响列表的索引,在循环之后,你可以使用包含所有应该删除的值的列表的新的空列表来删除它。
https://stackoverflow.com/questions/42486366
复制相似问题