using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace demMalyhin { public partial class AddAdmProduct : Form { private byte[] imageData = null; public AddAdmProduct() { InitializeComponent(); LoadCategories(); LoadManufacturers(); LoadSuppliers(); } private void LoadCategories() { DB db = new DB(); DataTable categories = new DataTable(); MySqlDataAdapter adapter = new MySqlDataAdapter(); MySqlCommand command = new MySqlCommand("SELECT Category_name FROM Category", db.getConnection()); try { db.openConnection(); adapter.SelectCommand = command; adapter.Fill(categories); comboBoxCategory.DataSource = categories; comboBoxCategory.DisplayMember = "Category_name"; comboBoxCategory.ValueMember = "Category_name"; } catch (Exception ex) { MessageBox.Show("Ошибка загрузки категорий " + ex.Message); } finally { db.closeConnection(); } } private void LoadSuppliers() { DB db = new DB(); DataTable suppliers = new DataTable(); MySqlDataAdapter adapter = new MySqlDataAdapter(); MySqlCommand command = new MySqlCommand("SELECT supplier_name FROM Supplier", db.getConnection()); try { db.openConnection(); adapter.SelectCommand = command; adapter.Fill(suppliers); comboBoxSupplier.DataSource = suppliers; comboBoxSupplier.DisplayMember = "supplier_name"; comboBoxSupplier.ValueMember = "supplier_name"; } catch (Exception ex) { MessageBox.Show("Ошибка загрузки категорий " + ex.Message); } finally { db.closeConnection(); } } private void LoadManufacturers() { DB db = new DB(); DataTable Manufacturer = new DataTable(); MySqlDataAdapter adapter = new MySqlDataAdapter(); MySqlCommand command = new MySqlCommand("SELECT Manufacturer_name FROM Manufacturer", db.getConnection()); try { db.openConnection(); adapter.SelectCommand = command; adapter.Fill(Manufacturer); comboBoxManufacturer.DataSource = Manufacturer; comboBoxManufacturer.DisplayMember = "Manufacturer_name"; comboBoxManufacturer.ValueMember = "Manufacturer_name"; } catch (Exception ex) { MessageBox.Show("Ошибка загрузки категорий " + ex.Message); } finally { db.closeConnection(); } } private void btnChooseImage_Click(object sender, EventArgs e) { openFileDialogImage.Filter = "Image Files (*.png;*.jpg;*.jpeg)|*.png;*.jpg;*.jpeg"; openFileDialogImage.Title = "Выберите изображение товара"; if (openFileDialogImage.ShowDialog() == DialogResult.OK) { try { string filePath = openFileDialogImage.FileName; // Если pictureBoxProductImage еще нет, создайте его в дизайнере if (pictureBoxProductImage != null) { pictureBoxProductImage.Image = Image.FromFile(filePath); pictureBoxProductImage.SizeMode = PictureBoxSizeMode.Zoom; } using (var ms = new MemoryStream()) { // Загружаем в MemoryStream, чтобы сохранить исходный формат using (Image originalImage = Image.FromFile(filePath)) { originalImage.Save(ms, originalImage.RawFormat); imageData = ms.ToArray(); } } // Опционально: можно добавить сообщение пользователю // MessageBox.Show("Изображение выбрано."); } catch (Exception ex) { MessageBox.Show("Ошибка при загрузке изображения: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); // Сбрасываем при ошибке if (pictureBoxProductImage != null) pictureBoxProductImage.Image = null; imageData = null; } } } private async void btnAdd_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBoxName.Text) || string.IsNullOrEmpty(textBoxArticle.Text) || string.IsNullOrEmpty(textBoxPrice.Text) || string.IsNullOrEmpty(textBoxSale.Text) || string.IsNullOrEmpty(textBoxUnit.Text) || string.IsNullOrEmpty(textBoxDesc.Text) || string.IsNullOrEmpty(textBoxQuantity.Text)) { MessageBox.Show("Заполните все обязательные поля!"); return; } if (!int.TryParse(textBoxQuantity.Text, out int quantity) || quantity <= 0) { MessageBox.Show("Пожалуйста, введите корректное значение количества"); return; } if (!decimal.TryParse(textBoxPrice.Text, out decimal price) || price <= 0) { MessageBox.Show("Пожалуйста введите корректное значение цены"); return; } DB db = new DB(); try { db.openConnection(); string query = "INSERT INTO products (article_product, product_name, price, supplier_id, manufacturer_id, category_id, sale_percent, unit_type, description, quantity_in_stock, photo)" + "VALUES (@article, @pr_name, @price, (SELECT id_Supplier FROM Supplier WHERE supplier_name = @sup_name), (SELECT id_Manufacturer FROM Manufacturer WHERE Manufacturer_name = @manu_name), (SELECT id_Category FROM Category WHERE Category_name = @category), @sale, @unit, @desc, @quantity, @product_photo)"; using (MySqlCommand command = new MySqlCommand(query, db.getConnection())) { command.Parameters.AddWithValue("@article", textBoxArticle.Text); command.Parameters.AddWithValue("@pr_name", textBoxName.Text); command.Parameters.AddWithValue("@price", price); command.Parameters.AddWithValue("@sup_name", comboBoxSupplier.SelectedValue.ToString()); command.Parameters.AddWithValue("@manu_name", comboBoxManufacturer.SelectedValue.ToString()); command.Parameters.AddWithValue("@category", comboBoxCategory.SelectedValue.ToString()); command.Parameters.AddWithValue("@sale", textBoxSale.Text); command.Parameters.AddWithValue("@unit", textBoxUnit.Text); command.Parameters.AddWithValue("@desc", textBoxDesc.Text); command.Parameters.AddWithValue("@quantity", quantity); if (imageData != null) { // Если изображение было выбрано command.Parameters.Add(new MySqlParameter("@product_photo", MySqlDbType.MediumBlob) { Value = imageData }); } else { // Если изображение не было выбрано, записываем NULL command.Parameters.Add(new MySqlParameter("@product_photo", MySqlDbType.MediumBlob) { Value = DBNull.Value }); } int rowsAffected = await command.ExecuteNonQueryAsync(); if (rowsAffected > 0) { MessageBox.Show("Товар успешно добавлен!"); DialogResult = DialogResult.OK; Close(); } else { MessageBox.Show("Ошибка при добавлении продукта."); } } } catch (MySqlException ex) { if (ex.Number == 1452) { MessageBox.Show("Указанная категория не существует. Введите допустимое название категории."); } else { MessageBox.Show("Ошибка базы данных: " + ex.Message); } } catch (Exception ex) { MessageBox.Show("Произошла: " + ex.Message); } finally { db.closeConnection(); } } private void btnBack_Click(object sender, EventArgs e) { this.Close(); AdmMainForm amf = new AdmMainForm(); amf.Show(); } } }