ProjectLib/ProjectLibrary/Forms/FBook.cs

103 lines
3.2 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;
//checkedListBox1.SelectedItem = book.TypeBookID;
char[] listInd = Convert.ToString((int)book.TypeBookID, 2).ToCharArray();
for (int i = 0; i < listInd.Length; i++)
{
checkedListBox1.SetItemChecked(i, listInd[i]=='1');
}
_bookId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
public FBook(IBookRepository bookRepository)
{
InitializeComponent();
_bookRepository = bookRepository ?? throw new ArgumentNullException(nameof(bookRepository));
foreach(var elem in Enum.GetValues(typeof(BookType)))
{
if (!elem.Equals(BookType.None)) checkedListBox1.Items.Add(elem);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(txtAuthor.Text) || string.IsNullOrWhiteSpace(txtName.Text))
{
throw new Exception("Имеются незаполненные поля.");
}
if (_bookId.HasValue)
{
_bookRepository.UpdateBook(CreateBook(_bookId.Value));
}
else
{
_bookRepository.CreateBook(CreateBook(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private Book CreateBook(int bookId)
{
BookType selectedType = BookType.None;
foreach (var item in checkedListBox1.CheckedItems)
{
if (item is BookType type)
{
selectedType |= type; // Это должно работать, если тип является BookType
}
}
return Book.CreateEntity(bookId, txtAuthor.Text, txtName.Text, selectedType);
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}