2017-02-27 53 views
0

我使用的是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(); 
    } 
+0

你不能修改迭代變量,而是修改你正在迭代的集合。 – C4u

+0

可能重複[有效地從'foreach'內刪除項目](http://stackoverflow.com/questions/8791557/efficiently-deleting-item-from-within-foreach) – klashar

+0

可能重複的[爲什麼我不能修改循環變量在foreach?](http://stackoverflow.com/questions/3551696/why-cant-i-modify-the-loop-variable-in-a-foreach) – C4u

回答

2

您好,我認爲問題在於您正在使用cartlist for循環,同時您希望刪除相同的值,這是不可能的。

只是你需要改變你的方法,如創建空列表,並添加所有的索引,從你必須刪除的值從底部到頂部像從列表的末尾,以便它不能影響索引該列表按刪除的值和循環後,可以使用包含應刪除的所有值的列表的新空列表將其刪除。

+0

謝謝!這解決了我的問題,我的英雄無角!我會在1分鐘內接受答案。 您的評論讓我更瞭解情況。我做了一個臨時產品,當foreach中的if語句被實現時,它獲得了p產品的價值。 –

+0

謝謝@albinaberg –