using ProjectGarage.Entities; using ProjectGarage.Entities.Enums; using ProjectGarage.Repositories; namespace ProjectGarage.Forms { public partial class FormTruck : Form { private readonly ITruckRepository _truckRepository; private int? _truckId; public int Id { set { try { var truck = _truckRepository.ReadTruckByID(value); if (truck == null) { throw new InvalidDataException(nameof(truck)); } textBoxTruckNumbers.Text = truck.Numbers; comboBoxTruckType.SelectedItem = truck.Type; numericUpDownMaxFuel.Value = truck.MaxFuel; _truckId = value; } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } public FormTruck(ITruckRepository truckRepository) { InitializeComponent(); _truckRepository = truckRepository ?? throw new ArgumentNullException(nameof(truckRepository)); comboBoxTruckType.DataSource = Enum.GetValues(typeof(TruckType)); } private void ButtonTruckSave_Click(object sender, EventArgs e) { try { if (string.IsNullOrWhiteSpace(textBoxTruckNumbers.Text) || comboBoxTruckType.SelectedIndex < 1) { throw new Exception("Имеются незаполненные поля"); } if (_truckId.HasValue) { _truckRepository.UpdateTruck(CreateTruck(_truckId.Value)); } else { _truckRepository.CreateTruck(CreateTruck(0)); } Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ButtonTruckCancel_Click(object sender, EventArgs e) => Close(); private Truck CreateTruck(int id) => Truck.CreateTruck(id, textBoxTruckNumbers.Text, (TruckType)comboBoxTruckType.SelectedItem!, Convert.ToInt32(numericUpDownMaxFuel.Value)); } }