2017-02-27 57 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 –