私はASP.netを使用しています。グリッドビューに削除ボタンを追加し、クリックしたボタンの行を削除しようとしました。私のforeachでInvalidOperationExceptionを取得することです。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>
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();
}
反復変数または反復処理しているコレクションを変更できません。 – 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