0303/0303RogovaNeshina/AddBooksForm.cs
2026-03-03 15:44:38 +04:00

110 lines
4.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Data;
using System.Windows.Forms;
using System.Xml.Linq;
using MySql.Data.MySqlClient;
namespace _0303RogovaNeshina
{
public partial class AddBooksForm : Form
{
string connStr = "Server=cfif31.ru;Port=3306;Database=ISPr25-21_NeshinaPV_0303;Uid=ISPr25-21_NeshinaPV;Pwd=ISPr25-21_NeshinaPV;";
public AddBooksForm()
{
InitializeComponent();
LoadAuthors(); // Загружаем авторов при открытии формы
}
// Метод загрузки авторов в ComboBox
private void LoadAuthors()
{
try
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
string sql = "SELECT idauthor, name FROM author ORDER BY name";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
// Настраиваем ComboBox
cbAuthor.DataSource = dt;
cbAuthor.DisplayMember = "name"; // Что показывать пользователю
cbAuthor.ValueMember = "idauthor"; // Что хранить внутри (ID автора)
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка загрузки авторов: " + ex.Message, "Критическая ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
// Проверка заполненности полей
if (string.IsNullOrWhiteSpace(tbName.Text))
{
MessageBox.Show("Введите название книги!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
tbName.Focus();
return;
}
if (cbAuthor.SelectedValue == null)
{
MessageBox.Show("Выберите автора!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
cbAuthor.Focus();
return;
}
decimal price;
if (!decimal.TryParse(tbPrice.Text, out price) || price <= 0)
{
MessageBox.Show("Введите корректную цену (больше 0)!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
tbPrice.Focus();
return;
}
try
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
string sql = "INSERT INTO books (name, author_id, price) VALUES (@name, @author_id, @price)";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@name", tbName.Text.Trim());
cmd.Parameters.AddWithValue("@author_id", cbAuthor.SelectedValue); // Берем ID из ComboBox
cmd.Parameters.AddWithValue("@price", price);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
MessageBox.Show("Книга успешно добавлена!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.DialogResult = DialogResult.OK;
this.Close();
}
else
{
MessageBox.Show("Не удалось добавить книгу.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при сохранении: " + ex.Message, "Критическая ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
}
}