COP_Petrushin_PIbd-32/Laba3/ProductForm.cs

97 lines
3.0 KiB
C#
Raw Normal View History

2024-10-30 13:34:23 +04:00
using Data;
using Data.Models;
using Data.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Laba3
{
public partial class ProductForm : Form
{
private readonly IProductRepository _productRepository;
private readonly IManufacturerRepository _manufacturerRepository;
private Product _product;
private bool _isNewProduct;
public ProductForm(IProductRepository productRepository, IManufacturerRepository manufacturerRepository, Product product = null)
{
InitializeComponent();
_productRepository = productRepository;
_manufacturerRepository = manufacturerRepository;
_product = product;
_isNewProduct = product == null;
if (!_isNewProduct)
{
txtName.Text = _product.Name;
cmbManufacturer.SelectedItem = _product.ManufacturerName;
dtpDeliveryDate.Value = _product.DeliveryDate;
if (_product.Image != null)
{
using (var ms = new MemoryStream(_product.Image))
{
pbImage.Image = Image.FromStream(ms);
}
}
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
using (var openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pbImage.Image = Image.FromFile(openFileDialog.FileName);
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtName.Text))
{
MessageBox.Show("Name is required.");
return;
}
if (_isNewProduct)
{
_product = new Product();
_productRepository.AddProduct(_product);
}
_product.Name = txtName.Text;
_product.ManufacturerName = cmbManufacturer.SelectedItem.ToString();
_product.DeliveryDate = dtpDeliveryDate.Value;
if (pbImage.Image != null)
{
using (var ms = new MemoryStream())
{
pbImage.Image.Save(ms, pbImage.Image.RawFormat);
_product.Image = ms.ToArray();
}
}
_productRepository.UpdateProduct(_product);
DialogResult = DialogResult.OK;
Close();
}
private void ProductForm_Load(object sender, EventArgs e)
{
var manufacturers = _manufacturerRepository.GetAllManufacturers().Select(m => m.Name).ToList();
cmbManufacturer.DataSource = manufacturers;
}
}
}