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

144 lines
5.6 KiB
C#
Raw 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 MySql.Data.MySqlClient;
namespace _0303RogovaNeshina
{
public partial class MainForm : Form
{
string connStr = "Server=cfif31.ru;Port=3306;Database=ISPr25-21_NeshinaPV_0303;Uid=ISPr25-21_NeshinaPV;Pwd=ISPr25-21_NeshinaPV;";
public MainForm()
{
InitializeComponent();
this.Load += MainForm_Load;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.ReadOnly = true;
}
private void MainForm_Load(object sender, EventArgs e)
{
try
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
string sql = @"
SELECT b.idbooks, b.name AS book_name, a.name AS author_name, b.price
FROM books b
INNER JOIN author a ON b.author_id = a.idauthor
ORDER BY b.idbooks";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
int count = da.Fill(dt);
if (count == 0)
{
MessageBox.Show("В таблице нет данных!");
return;
}
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Visible = false; // Скрыть ID
dataGridView1.Columns[1].HeaderText = "Название книги";
dataGridView1.Columns[2].HeaderText = "Автор";
dataGridView1.Columns[3].HeaderText = "Цена (руб.)";
dataGridView1.Columns[3].DefaultCellStyle.Format = "N2";
dataGridView1.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка: " + ex.Message, "Критическая ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btAdd_Click(object sender, EventArgs e)
{
AddBooksForm add = new AddBooksForm();
if (add.ShowDialog() == DialogResult.OK)
{
MainForm_Load(sender, e);
}
}
private void btEdit_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null)
{
MessageBox.Show("Выберите строку для редактирования!", "Внимание");
return;
}
int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
EditBooksForm edit = new EditBooksForm(id);
if (edit.ShowDialog() == DialogResult.OK)
{
MainForm_Load(sender, e);
}
}
private void btDelete_Click_1(object sender, EventArgs e)
{
// 1. Проверка выделения
if (dataGridView1.CurrentRow == null)
{
MessageBox.Show("Выберите книгу для удаления!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// 2. Подтверждение действия
string bookName = dataGridView1.CurrentRow.Cells[1].Value.ToString();
DialogResult res = MessageBox.Show(
$"Вы действительно хотите удалить книгу \"{bookName}\"?\nЭто действие нельзя отменить.",
"Подтверждение удаления",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (res == DialogResult.Yes)
{
try
{
int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value);
using (MySqlConnection conn = new MySqlConnection(connStr))
{
conn.Open();
string sql = "DELETE FROM books WHERE idbooks = @id";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@id", id);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
MessageBox.Show($"Книга \"{bookName}\" успешно удалена!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
MainForm_Load(sender, e); // Обновить таблицу
}
else
{
MessageBox.Show("Ошибка: книга не найдена в базе.", "Ошибка");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при удалении: " + ex.Message, "Критическая ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}