如何通过in-class方法添加到列表框?

时间:2015-01-18 16:08:40

标签: c# winforms list oop listbox

我在商店类的addproductto store方法中有一个产品类和商店类。需要将它们分别添加到listbox1和listbox2。为什么我的代码不起作用?

Form1中:

     static public List<Product> plist = new List<Product>();
     static public List<Store> slist = new List<Store>();

     slist.Add(new Store { Name = "Bargin Basin" });
        slist.Add(new Store { Name = "SuperMart" });

        plist.Add(new Product { Label = "Potatoes", Price = 3.60 });
        plist.Add(new Product { Label = "Fish", Price = 4.49 });

        private void AddButton_Click(object sender, EventArgs e)
            {

            string curItem = comboBox1.SelectedItem.ToString();

            // Create New Product
            if (curItem == "Product")
            {
                FormP AP = new FormP();
                if (AP.ShowDialog() == DialogResult.OK)
                {
                    string _label = AP.textBox1.Text; double _price = Convert.ToDouble(AP.textBox2.Text);
                    var newproduct = new Product { Label = _label, Price = _price };                                                       
                    Store store = slist.Find(y => y == AP.comboBox1.SelectedItem);
                   // Store store = AP.comboBox1.SelectedItem as Store;                                    
                    AddProductsToStore(store, newproduct);
                    listBox2.EndUpdate();

                }
            }

  public static void AddProductsToStore(Store store, Product product)
        {
               store.AddProduct(product);
               MessageBox.Show(String.Format("Product {0} added to store {1}", product.Label, store.Name));      
        }

类:

   public class Store
    {
        //public virtual int Id { get; protected set; }
        public virtual string Name { get; set; }
        public virtual IList<Product> Products { get; set; }
        public virtual IList<Rab> Rabs { get; set; }

        public Store()
        {
            Products = new List<Product>();
            Rabs = new List<Rab>();
        }

        public virtual void AddProduct(Product product)
        {
            product.StoresStockedIn.Add(this);
            Products.Add(product);   
        }
}
   public class Product
    {
       // public virtual int Id { get; protected set; }
        public virtual string Label { get; set; }
        public virtual double Price { get; set; }
        public virtual Location Location { get; set; }
        public virtual IList<Store> StoresStockedIn { get; set; }

        public Product()
        {
            StoresStockedIn = new List<Store>();
        }
    }

没有发生任何问题,代码继续工作,但是在列表框中没有改变,只有问题代码中的程序创建项目才会显示((

0 个答案:

没有答案