| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- using RestaurantApp.DAL;
- using RestaurantApp.Models;
- using System;
- using System.Data;
- using System.Linq;
- using System.Windows.Forms;
- using System.Xml.Linq;
- namespace RestaurantApp
- {
- public partial class DishEditForm : Form
- {
- private DishRepository repo = new DishRepository();
- private Dish dish;
- private bool isEdit = false;
- public DishEditForm()
- {
- InitializeComponent();
- isEdit = false;
- dish = new Dish();
- this.Text = "Новое блюдо";
- LoadCategories();
- btnSave.Click += BtnSave_Click;
- btnCancel.Click += (s, e) => DialogResult = DialogResult.Cancel;
- }
- public DishEditForm(Dish existingDish)
- {
- InitializeComponent();
- isEdit = true;
- dish = existingDish;
- this.Text = "Редактирование блюда";
- LoadCategories();
- LoadData();
- btnSave.Click += BtnSave_Click;
- btnCancel.Click += (s, e) => DialogResult = DialogResult.Cancel;
- }
- private void LoadCategories()
- {
- var dtCategories = repo.GetCategories();
- var list = dtCategories.AsEnumerable().Select(r => new
- {
- category_id = r.Field<int>("category_id"),
- name = r.Field<string>("name")
- }).ToList();
- cmbCategory.DataSource = list;
- cmbCategory.DisplayMember = "name";
- cmbCategory.ValueMember = "category_id";
- if (!isEdit && cmbCategory.Items.Count > 0)
- cmbCategory.SelectedIndex = 0;
- }
- private void LoadData()
- {
- cmbCategory.SelectedValue = dish.CategoryId;
- txtName.Text = dish.Name;
- txtDescription.Text = dish.Description;
- numPrice.Value = dish.Price;
- numWeight.Value = dish.WeightG ?? 0;
- numCookTime.Value = dish.CookTimeMin ?? 0;
- chkAvailable.Checked = dish.IsAvailable;
- }
- private void SaveData()
- {
- dish.CategoryId = (int)cmbCategory.SelectedValue;
- dish.Name = txtName.Text.Trim();
- dish.Description = txtDescription.Text.Trim();
- dish.Price = numPrice.Value;
- dish.WeightG = numWeight.Value > 0 ? (int?)numWeight.Value : null;
- dish.CookTimeMin = numCookTime.Value > 0 ? (int?)numCookTime.Value : null;
- dish.IsAvailable = chkAvailable.Checked;
- if (string.IsNullOrWhiteSpace(dish.Name))
- throw new Exception("Введите название блюда");
- if (dish.Price <= 0)
- throw new Exception("Цена должна быть больше 0");
- if (isEdit)
- repo.Update(dish);
- else
- repo.Insert(dish);
- }
- private void BtnSave_Click(object sender, EventArgs e)
- {
- try
- {
- SaveData();
- DialogResult = DialogResult.OK;
- Close();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
- }
- }
- private void DishEditForm_Load(object sender, EventArgs e)
- {
- }
- }
- }
|