在C#中的其他类中添加和删除列表中的项

时间:2013-12-05 20:09:13

标签: c# list

我正在使用表单在C#中设置基本购物车。我已将一些产品加载到List<>可以在打开时显示,但我的问题是,当我从列表中添加或删除项目时<>然后退出菜单并再次打开商店,显示原始列表。我不确定如何在原始列表中显示的商店中添加或删除它?谢谢你的帮助。

public partial class frmMain : Form
{
    private List<Product> products = null;

    public List<Product> GetStock()
    {
        List<Product> products = new List<Product>();

        products.Add(new Product("D001", "Milk", "Dairy", 1.20m, 10, 1.027m));
        products.Add(new Product("D002", "Cheese", "Dairy", 2.80m, 20, 0.300m));
        products.Add(new Product("F001", "Apple", "Fruit", 0.50m, 10, 0.136m));
        products.Add(new Product("F002", "Orange", "Fruit", 0.80m, 20, 0.145m));
        products.Add(new Product("V001", "Tomato", "Veg", 2.50m, 15, 0.110m));
        products.Add(new Product("V002", "Onion", "Veg", 1.50m, 10, 0.105m));
        products.Add(new Product("M001", "Lamb", "Meat", 4.50m, 10, 0.340m));
        products.Add(new Product("M002", "Chicken", "Meat", 3.50m, 10, 0.907m));

        return products;
    }

}

public partial class frmAdminMenu : Form
{

    Product products = new Product();
    List<Product> tmpProducts = (new frmMain()).GetStock();


    private void btnAdminAddStock_Click(object sender, EventArgs e)
    {
        Product tmp = new Product(txtCode.Text, txtDescription.Text, category, Convert.ToDecimal(txtPrice.Text), 
            Convert.ToInt16(txtQuantity.Text), Convert.ToDecimal(txtWeight.Text));
        if (tmp != null)
            tmpProducts.Add(tmp);

        loadProducts();

    }

    private void frmAdminMenu_Load(object sender, EventArgs e)
    {
        string heading = "Code:\tDescription:\tCategory:\tPrice:\tStock:\tWeight:\n";
        lstViewStock.Text = heading.ToString();

        loadProducts();
    }

    private void loadProducts()
    {
        lstViewStock.Items.Clear();
        foreach (Product p in tmpProducts)
        {
            lstViewStock.Items.Add(p.GetDisplayText("\t"));
        }
    }

    private void btnAdminRemoveStock_Click(object sender, EventArgs e)
    {
        tmpProducts.RemoveAt(lstViewStock.SelectedIndex);

        //tmpProducts.RemoveAt(lstViewStock.SelectedItems);
        loadProducts();
    }


}

}

1 个答案:

答案 0 :(得分:0)

当你这样做时,

List<Product> tmpProducts = (new frmMain()).GetStock();

您正在将列表重新初始化回GetStockfrmMain返回的原始列表。这就是它在您打开新frmAdminMenu时显示相同列表的原因。

您应该尝试将列表保留为model对象的一部分,并在关闭表单时保存它(到数据库,文件系统,内存),以便保存更改,否则,表单不会真的做了什么。