ProjectLib/ProjectLibrary/Forms/FLibrary.cs

100 lines
3.3 KiB
C#
Raw Normal View History

2024-11-20 19:31:06 +04:00
using ProjectLibrary.Entites;
2024-12-03 20:14:30 +04:00
using ProjectLibrary.Repositores;
2024-11-20 19:31:06 +04:00
using ProjectLibrary.Repositories;
using ProjectLibrary.Repositories.Implementations;
2024-11-19 14:49:58 +04:00
using System.Windows.Forms;
2024-11-20 19:31:06 +04:00
2024-11-19 14:49:58 +04:00
namespace ProjectLibrary.Forms
{
public partial class FLibrary : Form
{
2024-11-20 19:31:06 +04:00
private readonly ILibraryRepository _libraryRepository;
private int? _orderId;
public int Id
2024-11-19 14:49:58 +04:00
{
2024-11-20 19:31:06 +04:00
set
{
try
{
var library = _libraryRepository.ReadLibraryById(value);
if (library == null)
{
throw new InvalidOperationException("Заказ не найден.");
}
txtName.Text = library.Name;
txtAddress.Text = library.Address;
dataGridView.DataSource = library.BookLibrary;
_orderId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
2024-11-19 14:49:58 +04:00
}
2024-12-03 20:14:30 +04:00
public FLibrary(ILibraryRepository libraryRepository, IBookRepository bookRepository)
2024-11-19 14:49:58 +04:00
{
2024-11-20 19:31:06 +04:00
InitializeComponent();
_libraryRepository = libraryRepository ?? throw new ArgumentNullException(nameof(libraryRepository));
2024-12-03 20:14:30 +04:00
Book.DataSource = bookRepository.ReadBooks();
Book.DisplayMember = "Name";
Book.ValueMember = "Id";
2024-11-19 14:49:58 +04:00
}
2024-11-20 19:31:06 +04:00
private void ButtonSave_Click(object sender, EventArgs e)
2024-11-19 14:49:58 +04:00
{
2024-11-20 19:31:06 +04:00
try
{
if (string.IsNullOrWhiteSpace(txtName.Text) || string.IsNullOrWhiteSpace(txtAddress.Text))
{
throw new Exception("Не все поля заполнены.");
}
var library = Library.CreateEntity(
_orderId ?? 0,
txtName.Text,
txtAddress.Text,
CreateListBooksFromDataGrid()
);
if (_orderId.HasValue)
{
_libraryRepository.UpdateLibrary(library);
}
else
{
_libraryRepository.CreateLibrary(library);
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
2024-11-19 14:49:58 +04:00
}
private void buttonCancel_Click_Click(object sender, EventArgs e)
{
2024-11-19 15:04:19 +04:00
this.Close();
2024-11-19 14:49:58 +04:00
}
2024-11-20 19:31:06 +04:00
private List<Book_Library> CreateListBooksFromDataGrid()
{
var list = new List<Book_Library>();
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["Book"].Value == null || row.Cells["Count"].Value == null)
{
continue;
}
list.Add(Book_Library.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnBook"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value)));
}
return list;
}
2024-11-19 14:49:58 +04:00
}
}