using MySql.Data.MySqlClient; 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; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox; namespace NeshinaPolina07_11 { public partial class AddProduct : Form { private _1Menu parentForm; public AddProduct(_1Menu parent) { InitializeComponent(); parentForm = parent; LoadCategories(); LoadManufacturers(); LoadSuppliers(); } private void LoadCategories() { cmbCategory.Items.Clear(); try { var db = DB.GetInstance(); var connection = db.GetConnection(); string query = "SELECT category_id, category_name FROM categories ORDER BY category_name"; using (MySqlCommand cmd = new MySqlCommand(query, connection)) using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { cmbCategory.Items.Add(new CategoryItem { Id = Convert.ToInt32(reader["category_id"]), Name = reader["category_name"].ToString() }); } } } catch (Exception ex) { MessageBox.Show("Ошибка загрузки категорий: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } cmbCategory.DisplayMember = "Name"; cmbCategory.ValueMember = "Id"; if (cmbCategory.Items.Count > 0) cmbCategory.SelectedIndex = 0; } private void LoadManufacturers() { cmbManufacturer.Items.Clear(); try { var db = DB.GetInstance(); var connection = db.GetConnection(); string query = "SELECT manufacturer_id, manufacturer_name FROM manufacturers ORDER BY manufacturer_name"; using (MySqlCommand cmd = new MySqlCommand(query, connection)) using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { cmbManufacturer.Items.Add(new ManufacturerItem { Id = Convert.ToInt32(reader["manufacturer_id"]), Name = reader["manufacturer_name"].ToString() }); } } } catch (Exception ex) { MessageBox.Show("Ошибка загрузки производителей: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } cmbManufacturer.DisplayMember = "Name"; cmbManufacturer.ValueMember = "Id"; if (cmbManufacturer.Items.Count > 0) cmbManufacturer.SelectedIndex = 0; } private void LoadSuppliers() { cmbSupplier.Items.Clear(); try { var db = DB.GetInstance(); var connection = db.GetConnection(); string query = "SELECT supplier_id, supplier_name FROM suppliers ORDER BY supplier_name"; using (MySqlCommand cmd = new MySqlCommand(query, connection)) using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { cmbSupplier.Items.Add(new SupplierItem { Id = Convert.ToInt32(reader["supplier_id"]), Name = reader["supplier_name"].ToString() }); } } } catch (Exception ex) { MessageBox.Show("Ошибка загрузки поставщиков: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } cmbSupplier.DisplayMember = "Name"; cmbSupplier.ValueMember = "Id"; if (cmbSupplier.Items.Count > 0) cmbSupplier.SelectedIndex = 0; } private class CategoryItem { public int Id { get; set; } public string Name { get; set; } public override string ToString() => Name; } private class ManufacturerItem { public int Id { get; set; } public string Name { get; set; } public override string ToString() => Name; } private class SupplierItem { public int Id { get; set; } public string Name { get; set; } public override string ToString() => Name; } private int? GetCategoryId() => cmbCategory.SelectedItem is CategoryItem c ? c.Id : (int?)null; private int? GetManufacturerId() => cmbManufacturer.SelectedItem is ManufacturerItem m ? m.Id : (int?)null; private int? GetSupplierId() => cmbSupplier.SelectedItem is SupplierItem s ? s.Id : (int?)null; private void textBox5_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txtArticle.Text) || string.IsNullOrWhiteSpace(txtName.Text)) { MessageBox.Show("Артикул и название товара обязательны для заполнения.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (!string.IsNullOrWhiteSpace(txtPrice.Text)) { if (!decimal.TryParse(txtPrice.Text.Replace(',', '.'), out decimal price) || price < 0) { MessageBox.Show("Цена должна быть положительным числом (например: 199.99).", "Некорректная цена", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtPrice.Focus(); return; } } if (!string.IsNullOrWhiteSpace(txtDiscount.Text)) { if (!int.TryParse(txtDiscount.Text, out int discount) || discount < 0 || discount > 100) { MessageBox.Show("Скидка должна быть целым числом от 0 до 100%.", "Некорректная скидка", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtDiscount.Focus(); return; } } if (!string.IsNullOrWhiteSpace(txtQuantity.Text)) { if (!int.TryParse(txtQuantity.Text, out int quantity) || quantity < 0) { MessageBox.Show("Количество должно быть целым неотрицательным числом (0 или больше).", "Некорректное количество", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtQuantity.Focus(); return; } } try { var db = DB.GetInstance(); var connection = db.GetConnection(); string query = @" INSERT INTO products ( product_article, product_name, unit, price, discount, quantity_in_stock, description, category_id, manufacturer_id, supplier_id ) VALUES ( @article, @name, 'шт.', @price, @discount, @quantity, @description, @categoryId, @manufacturerId, @supplierId )"; using (MySqlCommand cmd = new MySqlCommand(query, connection)) { cmd.Parameters.AddWithValue("@article", txtArticle.Text.Trim()); cmd.Parameters.AddWithValue("@name", txtName.Text.Trim()); if (decimal.TryParse(txtPrice.Text.Replace(',', '.'), out decimal parsedPrice)) cmd.Parameters.AddWithValue("@price", parsedPrice); else cmd.Parameters.AddWithValue("@price", DBNull.Value); if (int.TryParse(txtDiscount.Text, out int parsedDiscount)) cmd.Parameters.AddWithValue("@discount", parsedDiscount); else cmd.Parameters.AddWithValue("@discount", DBNull.Value); if (int.TryParse(txtQuantity.Text, out int parsedQuantity)) cmd.Parameters.AddWithValue("@quantity", parsedQuantity); else cmd.Parameters.AddWithValue("@quantity", DBNull.Value); cmd.Parameters.AddWithValue("@description", string.IsNullOrWhiteSpace(txtDescription.Text) ? (object)DBNull.Value : txtDescription.Text.Trim()); cmd.Parameters.AddWithValue("@categoryId", GetCategoryId() ?? (object)DBNull.Value); cmd.Parameters.AddWithValue("@manufacturerId", GetManufacturerId() ?? (object)DBNull.Value); cmd.Parameters.AddWithValue("@supplierId", GetSupplierId() ?? (object)DBNull.Value); if (cmd.ExecuteNonQuery() > 0) { MessageBox.Show("Товар успешно добавлен!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); parentForm.RefreshData(); this.Close(); } else { MessageBox.Show("Не удалось добавить товар.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (Exception ex) { MessageBox.Show("Ошибка при добавлении товара: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }