COP3PLUSSagirov/DeliveryApp/FormType.cs

123 lines
4.0 KiB
C#
Raw Normal View History

using Contracts.BindingModels;
using Contracts.BuisnessLogicsContracts;
using Contracts.ViewModels;
using Microsoft.EntityFrameworkCore.Diagnostics;
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;
namespace DeliveryApp
{
public partial class FormType : Form
{
private readonly ITypeLogic _logic;
List<TypeViewModel>? _list;
public FormType(ITypeLogic logic)
{
InitializeComponent();
_logic = logic;
}
private void FormType_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
_list = _logic.ReadList(null);
if (_list != null)
{
dataGridView.DataSource = _list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["PostType"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
}
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
if (dataGridView.SelectedCells[1].Value == null)
{
throw new Exception("Ошибка, нельзя сохранить пустую строку");
}
int _id;
bool id = Int32.TryParse(dataGridView.SelectedRows[0].Cells["Id"].Value?.ToString(), out _id);
if (_id == -1)
{
id = false;
}
var model = new TypeBindingModel
{
Id = id ? _id : 0,
PostType = dataGridView.SelectedCells[1].Value.ToString()!,
};
var operationResult = id ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении.");
}
LoadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Insert)
{
_list?.Add(new TypeViewModel { Id = -1, PostType = "" });
if (_list != null)
{
dataGridView.DataSource = null;
dataGridView.DataSource = _list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["PostType"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
if(e.KeyCode == Keys.Delete)
{
if (MessageBox.Show("Вы уверены?", "Удалить", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
int _id;
bool id = Int32.TryParse(dataGridView.SelectedRows[0].Cells["Id"].Value?.ToString(), out _id);
if (_id == -1 || !id)
{
id = false;
return;
}
var model = new TypeBindingModel
{
Id = _id,
PostType = dataGridView.SelectedCells[1].Value.ToString()!,
};
_logic.Delete(model);
LoadData();
}
}
}
}