// calls to delete the product with that name private void btnDelete_Click(object sender, EventArgs e) { ClearErrors(); // get the name of the product to be deleted string inputName = txtName.Text + "".Trim(); if (string.IsNullOrWhiteSpace(inputName)) { lblErrors.Text = "Need a name to remove.\n"; return; } List <GBRProduct> products = (List <GBRProduct>)lstProducts.DataSource; GBRProduct inFile = products.FirstOrDefault(p => p.ProductName.ToLower().Equals(inputName.ToLower())); if (inFile is null) { lblErrors.Text = "Product doesn't exist.\n"; return; } try { inFile.GBRDelete(inFile); ReloadListBox(); lblErrors.Text = $"{inputName} was successfully deleted.\n"; } catch (Exception ex) { lblErrors.Text = ex.Message; } }
// save a new product or update the current product private void btnSave_Click(object sender, EventArgs e) { ClearErrors(); try { ValidateForm(); // if valid... instantiate and save. string inputName = txtName.Text + "".Trim(), inputDescription = txtDescription.Text + "".Trim(), inputPrice = txtPrice.Text + "".Trim(), inputFactor = txtFactor.Text + "".Trim(); var product = GBRProduct.Parse(inputName + "\t" + inputPrice + "\t" + inputFactor + "\t" + chkTopping.Checked.ToString() + "\t" + inputDescription); if (GBRProduct.GBRGetByProductName(inputName) is null) { product.GBRAdd(product); lblErrors.Text = $"Add {inputName} to file successfully."; ReloadListBox(inputName); //lstProducts.SelectedValue = inputName; } else { DialogResult result = MessageBox.Show($"Do you want to update the product {inputName}?", "Update product", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { product.GBRUpdate(product); lblErrors.Text = $"Updated {inputName} to file successfully."; ReloadListBox(inputName); } } } catch (Exception ex) { lblErrors.Text += ex.Message; } }
// Fill the form with the Product information private void FillTheForm(GBRProduct product) { ClearErrors(); txtName.Text = product.ProductName; txtPrice.Text = product.Price.ToString("F2", CULTURE.NumberFormat); txtFactor.Text = product.CostFactorForToppings.ToString("F2", CULTURE.NumberFormat); txtDescription.Text = product.Description; chkTopping.Checked = product.IsPizzaTopping; }
// Reloads the list box using a optional key private void ReloadListBox(string key = "") { List <GBRProduct> products = GBRProduct.GBRGetProducts(); products = products.OrderBy(p => p.ProductName).ToList(); lstProducts.DisplayMember = "ProductName"; lstProducts.ValueMember = "ProductName"; lstProducts.DataSource = products; if (key != "") { lstProducts.SelectedValue = key; } }
// Use case of selecting some item in the list box private void lstProducts_SelectedIndexChanged(object sender, EventArgs e) { ClearErrors(); var input = lstProducts.SelectedValue.ToString(); var product = GBRProduct.GBRGetByProductName(input); if (product is null) { lblErrors.Text = "Can't find the product.\n"; } else { FillTheForm(product); } }