ProjectLib/ProjectLibrary/Forms/FOrder.cs

96 lines
3.1 KiB
C#
Raw Normal View History

using ProjectLibrary.Repositories;
using ProjectLibrary.Entites;
2024-11-20 19:31:06 +04:00
using System.Xml.Linq;
namespace ProjectLibrary.Forms
{
public partial class FOrder : Form
{
private readonly IOrderRepository _orderRepository;
private int? _orderId;
2024-11-20 19:31:06 +04:00
public FOrder(IOrderRepository orderRepository)
{
InitializeComponent();
2024-11-20 19:31:06 +04:00
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
}
2024-11-20 19:31:06 +04:00
public int Id
{
set
{
2024-11-20 19:31:06 +04:00
try
{
var order = _orderRepository.ReadOrderById(value);
if (order == null)
{
throw new InvalidOperationException("Заказ не найден.");
}
2024-11-20 19:31:06 +04:00
txtOrderDate.Text = order.OrderDate.ToString();
txtReturnDate.Text = order.ReturnDate.ToString();
comboBox.SelectedItem = order.ReaderID;
dataGridViewBook.DataSource = order.BookOrders;
_orderId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
2024-11-20 19:31:06 +04:00
private List<Book_Orders> CreateListBooksFromDataGrid()
{
var list = new List<Book_Orders>();
2024-11-20 19:31:06 +04:00
foreach (DataGridViewRow row in dataGridViewBook.Rows)
{
2024-11-20 19:31:06 +04:00
if (row.Cells["ColumnBook"].Value == null)
{
continue;
}
2024-11-20 19:31:06 +04:00
list.Add(Book_Orders.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnBook"].Value)));
}
return list;
}
2024-11-20 19:31:06 +04:00
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
2024-11-20 19:31:06 +04:00
if (string.IsNullOrWhiteSpace(txtOrderDate.Text) || string.IsNullOrWhiteSpace(txtReturnDate.Text) || comboBox.SelectedItem == null)
{
throw new Exception("Не все поля заполнены.");
}
2024-11-20 19:31:06 +04:00
var order = Orders.CreateEntity(
_orderId ?? 0,
DateTime.Parse(txtOrderDate.Text),
DateTime.Parse(txtReturnDate.Text),
2024-11-20 19:31:06 +04:00
int.Parse(comboBox.SelectedItem.ToString()),
CreateListBooksFromDataGrid()
);
if (_orderId.HasValue)
{
2024-11-20 19:31:06 +04:00
_orderRepository.UpdateOrder(order);
}
else
{
2024-11-20 19:31:06 +04:00
_orderRepository.CreateOrder(order);
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}