public Form1() { InitializeComponent(); _cart = ShoppingCart.GetShoppingCart(); _repo = new PizzaRepo(); // Event handling -> Hook up the delegate in the User Control class to a listener in this class //myUserControl1.AddToCartButtonClicked += AddToCartButtonClickedInUserControl; //myUserControl2.AddToCartButtonClicked += AddToCartButtonClickedInUserControl; //myUserControl3.AddToCartButtonClicked += AddToCartButtonClickedInUserControl; //myUserControl4.AddToCartButtonClicked += AddToCartButtonClickedInUserControl; //myUserControl5.AddToCartButtonClicked += AddToCartButtonClickedInUserControl; // Do the same but dynamic. Foreach MyUserControl in control, hook up listener foreach (var control in this.Controls) { MyUserControl myUserControl = control as MyUserControl; if (myUserControl != null) { myUserControl.AddToCartButtonClicked += AddToCartButtonClickedInUserControl; } } }
// Event Handler -> Listeners, Listens for Events // Catch event from children classes(User Controls) private void AddToCartButtonClickedInUserControl(object sender, EventArgs e) { // Cast object class to MyUserClass MyUserControl myControl = sender as MyUserControl; int productId = myControl.PizzaID; AddProductToCart(productId); }
private void GenerateControlsForPizzas(IEnumerable <IPizza> pizzas) { foreach (IPizza pizza in pizzas) { MyUserControl myUserControl = new MyUserControl { PizzaID = pizza.ID, MyProductName = pizza.Name, Price = pizza.Price.ToString(), IsInStock = pizza.IsInStock, Comments = pizza.Comments, Image = pizza.Image }; flowLayoutPanel1.Controls.Add(myUserControl); } }