ProjectLib/ProjectLibrary/Forms/FBook.cs

85 lines
2.7 KiB
C#

using ProjectLibrary.Entities;
using ProjectLibrary.Entities.Enums;
using ProjectLibrary.Repositores;
using ProjectLibrary.Repositories;
namespace ProjectLibrary.Forms
{
public partial class FBook : Form
{
private readonly IBookRepository _bookRepository;
private int? _bookId;
public int Id
{
set
{
try
{
var book = _bookRepository.ReadBookById(value);
if (book == null)
{
throw new InvalidOperationException("Книга не найдена.");
}
txtAuthor.Text = book.Author;
txtName.Text = book.Name;
cmbType.SelectedItem = book.Type;
comboBoxLibrary.SelectedItem = book.LibraryID;
_bookId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
public FBook(IBookRepository bookRepository, ILibraryRepository libraryRepository)
{
InitializeComponent();
_bookRepository = bookRepository ?? throw new ArgumentNullException(nameof(bookRepository));
comboBoxLibrary.DataSource = libraryRepository.ReadLibraries();
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(txtAuthor.Text) || string.IsNullOrWhiteSpace(txtName.Text) || comboBoxLibrary.SelectedItem == null)
{
throw new Exception("Имеются незаполненные поля.");
}
var book = Book.CreateEntity(
_bookId ?? 0,
txtAuthor.Text,
txtName.Text,
(BookType)cmbType.SelectedValue,
Convert.ToInt32(comboBoxLibrary.SelectedItem)
);
if (_bookId.HasValue)
{
_bookRepository.UpdateBook(book);
}
else
{
_bookRepository.CreateBook(book);
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}