单击按钮从列表中删除

时间:2018-12-16 20:19:41

标签: c# list

我正在将列表中的项目分别打印到标签上,并在附近使用按钮将其从列表中删除。删除按钮似乎无效。

private void cart_Click(object sender, EventArgs e)
{
    krepselioPanel.Visible = !krepselioPanel.Visible;
    krepselioPav.Visible = !krepselioPav.Visible;

    int i = 0;
    double s = 0;

    foreach (Patiekalas preke in prekes)
    {
        Label prekiulist = new Label();

        prekiulist.Location = new Point(0, 26 * i);
        prekiulist.Text = preke.GetPatiekalas() + " | " + preke.GetKaina() + "€";
        prekiulist.Size = new Size(200, 20);
        krepselioPanel.Controls.Add(prekiulist);
        s += Convert.ToDouble(preke.GetKaina());

        Button removeButton = new Button();
        removeButton.Text = "x";
        removeButton.Location = new Point(200, 26 * i);
        removeButton.Font = new Font(FontFamily.GenericSansSerif, 9);
        removeButton.Size = new Size(20, 22);
        removeButton.Click += removeButton_Click;
        removeButton.Tag = preke;
        krepselioPanel.Controls.Add(removeButton);
        i++;
    }


    Label suma = new Label();
    suma.Location = new Point(krepselioPanel.Right - 140, 0);
    suma.Font = new Font(FontFamily.GenericSansSerif, 13);
    suma.Text = "Total: " + s + "€";
    suma.Size = new Size(130, 25);
    krepselioPanel.Controls.Add(suma);

}


private void removeButton_Click(object sender, EventArgs e)
{
    Button b = (Button)sender;
    Patiekalas preke = (Patiekalas)b.Tag;
    prekes.Remove(preke);
    cart_Click(sender, e);
    cart_Click(sender, e);
}

}

只是出于兴趣,我更改了功能removeButton_Click行

  

prekes.Remove(preke);

  

prekes.Add(preke);

,这将在列表中创建一个新条目,但是删除将不起作用。

1 个答案:

答案 0 :(得分:0)

该代码似乎并未从面板中删除以前的控件,因此每次添加控件时都会创建一个新控件。如果购物车中只有一件物品,则下次似乎什么也没发生,也没有添加或删除任何物品,但是如果有多个物品,它们将开始相乘。

因此,从面板中删除控件,然后添加新的控件,该项将消失。