PIbd-23_Baryshev_D.A._Garage/ProjectGarage/Forms/FormRoutes.cs

120 lines
3.6 KiB
C#

using ProjectGarage.Repositories;
using ProjectGarage.Repositories.Implementations;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Unity;
namespace ProjectGarage.Forms
{
public partial class FormRoutes : Form
{
private readonly IUnityContainer _container;
private readonly IRouteRepository _routeRepository;
public FormRoutes(IUnityContainer container, IRouteRepository routeRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_routeRepository = routeRepository ?? throw new ArgumentNullException(nameof(routeRepository));
}
private void ButtonAddRoute_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormRoute>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormRoutes_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDeleteRoute_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_routeRepository.DeleteRoute(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdateRoute_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormRoute>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridViewRoutes.DataSource = _routeRepository.ReadRoute();
dataGridViewRoutes.Columns["Id"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewRoutes.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id =
Convert.ToInt32(dataGridViewRoutes.SelectedRows[0].Cells["Id"].Value);
return true;
}
}
}