ISEbd-22_Rozhkov.I.E._Simple/GasStation/Forms/FormProduct.cs

80 lines
2.3 KiB
C#
Raw Normal View History

2024-11-15 18:27:06 +04:00
using GasStation.Entities.Enums;
using GasStation.Repositories;
using GasStation.Entities;
2024-12-02 14:38:24 +04:00
namespace GasStation.Forms;
2024-11-15 18:27:06 +04:00
2024-12-02 14:38:24 +04:00
public partial class FormProduct : Form
{
2024-11-15 18:27:06 +04:00
2024-12-02 14:38:24 +04:00
private readonly IProductRepository _productRepository;
2024-11-15 18:27:06 +04:00
2024-12-02 14:38:24 +04:00
private int? _productId;
2024-11-15 18:27:06 +04:00
2024-12-02 14:38:24 +04:00
public FormProduct(IProductRepository productRepository)
{
InitializeComponent();
_productRepository = productRepository ??
throw new ArgumentNullException(nameof(productRepository));
2024-11-15 18:27:06 +04:00
2024-12-02 14:38:24 +04:00
comboBoxProduct.DataSource = Enum.GetValues(typeof(ProductType));
}
2024-11-15 18:27:06 +04:00
2024-12-02 14:38:24 +04:00
public int ID
{
set
2024-11-15 18:27:06 +04:00
{
try
{
2024-12-02 14:38:24 +04:00
var product = _productRepository.ReadProductByID(value);
if (product == null)
2024-11-15 18:27:06 +04:00
{
2024-12-02 14:38:24 +04:00
throw new InvalidDataException(nameof(product));
2024-11-15 18:27:06 +04:00
}
2024-12-02 14:38:24 +04:00
textBoxProduct.Text = product.ProductName;
2024-12-02 14:38:24 +04:00
comboBoxProduct.SelectedItem = product.ProductType;
_productId = value;
2024-11-15 18:27:06 +04:00
}
catch (Exception ex)
{
2024-12-02 14:38:24 +04:00
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
2024-11-15 18:27:06 +04:00
return;
}
}
2024-12-02 14:38:24 +04:00
}
2024-11-15 18:27:06 +04:00
2024-12-02 14:38:24 +04:00
private void ButtonSave_Click(object sender, EventArgs e)
{
try
2024-11-15 18:27:06 +04:00
{
2024-12-02 14:38:24 +04:00
if (comboBoxProduct.SelectedIndex < 1)
2024-11-15 18:27:06 +04:00
{
2024-12-02 14:38:24 +04:00
throw new Exception("Имеются незаполненые поля");
2024-11-15 18:27:06 +04:00
}
2024-12-02 14:38:24 +04:00
if (_productId.HasValue)
{
_productRepository.UpdateProduct(CreateProduct(_productId.Value));
}
else
{
_productRepository.CreateProduct(CreateProduct(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
2024-11-15 18:27:06 +04:00
}
}
2024-12-02 14:38:24 +04:00
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Product CreateProduct(int id) =>
Product.CreateProduct(id, textBoxProduct.Text, Convert.ToInt32(numericUpDownCost.Value),
2024-12-02 14:38:24 +04:00
(ProductType)comboBoxProduct.SelectedItem!);
2024-11-15 18:27:06 +04:00
}