努力从列表<t>中删除项目,虽然我有列表中的项目<t>

时间:2017-08-22 11:02:31

标签: asp.net .net

当用户点击List< >按钮时,我试图在AddToCart中添加项目。最后,当用户点击List< >按钮时,我试图从RemoveFromCart删除项目。最后,我正在努力从List< >中移除该项目。任何人都可以帮助我。

public partial class Home : System.Web.UI.Page
{
    List<int> list1 = new List<int>();
    int inc;
    protected void listview1_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Buy")
        {
            int PC = int.Parse(e.CommandArgument.ToString());
            Response.Redirect("~/Buy.aspx?PC=" + PC);
        }
        if (e.CommandName == "AddToCart")
        {

            list1.Add(int.Parse(e.CommandArgument.ToString()));
                foreach (int i in list1)
                {
                    lbl.Text += i.ToString() + ",";
                    string length = lbl.Text.Length.ToString();
                    string sval = lbl.Text.Remove(int.Parse(length) - 1, 1);
                    lbl1.Text = sval.ToString();
                }           

            e.Item.FindControl("btnRemoveFromCart").Visible = true;
            inc = (int)ViewState["Increment"];
            ViewState["Increment"] = inc;
            inc += 1;
            lblitemscount.Text = inc.ToString();
            ViewState["Increment"] = inc;
        }
        if (e.CommandName == "RemoveFromCart")
        {
            int val = int.Parse(e.CommandArgument.ToString());
            inc = (int)ViewState["Increment"];
            ViewState["Increment"] = inc;
            inc -= 1;
            lblitemscount.Text = inc.ToString();
            ViewState["Increment"] = inc;
            foreach (int j in list1)
            {
                if (list1.Contains(val))
                {
                    list1.Remove(val);
                }
                lbl1.Text += j.ToString();
            }
            e.Item.FindControl("btnRemoveFromCart").Visible = false;
        }
    }
}


----------

1 个答案:

答案 0 :(得分:0)

您在迭代时无法从列表中删除项目。您需要找到该项目的索引,然后使用RemoveAt方法将其从列表中删除。

https://msdn.microsoft.com/en-us/library/5cw9x18z(v=vs.110).aspx