// 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; } }
// 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); } }