demMalyhinMerkulov/AddProductForm.cs
2025-11-25 12:59:48 +04:00

126 lines
4.1 KiB
C#

using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows.Forms;
namespace megadem
{
public partial class AddProductForm : Form
{
public AddProductForm()
{
InitializeComponent();
LoadTypes();
}
private void LoadTypes()
{
DB db = new DB();
DataTable types = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand("SELECT ProductType FROM Product_type", db.getConnection());
try
{
db.openConnection();
adapter.SelectCommand = command;
adapter.Fill(types);
comboBoxType.DataSource = types;
comboBoxType.DisplayMember = "ProductType";
comboBoxType.ValueMember = "ProductType";
}
catch (Exception ex)
{
MessageBox.Show("Ошибка загрузки типов " + ex.Message);
}
finally
{
db.closeConnection();
}
}
private async void btnAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(Article.Text) || string.IsNullOrEmpty(NameProd.Text) || string.IsNullOrEmpty(MinPrice.Text) || string.IsNullOrEmpty(Width.Text))
{
MessageBox.Show("Заполните все обязательные поля!");
return;
}
if (!decimal.TryParse(MinPrice.Text, out decimal price) || price <= 0)
{
MessageBox.Show("Пожалуйста введите корректное значение цены");
return;
}
DB db = new DB();
try
{
db.openConnection();
string query = "INSERT INTO Product (Product_type_id, Product_name, Article, Min_price_partner, Width)" +
"VALUES ((SELECT idProduct_type FROM Product_type WHERE ProductType = @type), @pr_name, @article, @price, @sale)";
using (MySqlCommand command = new MySqlCommand(query, db.getConnection()))
{
command.Parameters.AddWithValue("@article", Article.Text);
command.Parameters.AddWithValue("@pr_name", NameProd.Text);
command.Parameters.AddWithValue("@price", price);
command.Parameters.AddWithValue("@type", comboBoxType.SelectedValue.ToString());
command.Parameters.AddWithValue("@sale", Width.Text);
int rowsAffected = await command.ExecuteNonQueryAsync();
if (rowsAffected > 0)
{
MessageBox.Show("Товар успешно добавлен!");
DialogResult = DialogResult.OK;
this.Hide();
MainForm form = new MainForm();
form.Show();
}
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 button1_Click(object sender, EventArgs e)
{
this.Hide();
MainForm mainForm = new MainForm();
mainForm.Show();
}
}
}