COP_labs/OnlineShopForms/FormStatuses.cs

120 lines
4.3 KiB
C#
Raw Normal View History

using Microsoft.EntityFrameworkCore.Metadata.Internal;
using OnlineShopContracts.BindingModels;
using OnlineShopContracts.ViewModels;
using OnlineShopDatabase.Storages;
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 OnlineShopForms
{
public partial class FormStatuses : Form
{
private readonly StatusStorage _storage;
List<StatusViewModel> list;
public FormStatuses()
{
InitializeComponent();
_storage = new StatusStorage();
}
private void FormStatuses_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
list = _storage.GetFullList();
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Insert)
{
list.Add(new StatusViewModel());
dataGridView.DataSource = list;
dataGridView.CurrentCell = dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1];
}
else if (e.KeyData == Keys.Delete)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
try
{
if (!_storage.Delete(new StatusBindingModel() { Id = id }))
{
throw new Exception("Ошибка при удалении");
}
dataGridView.Rows.RemoveAt(dataGridView.SelectedRows[0].Index);
LoadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
//конец редактирования названия статуса (ячейки)
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//то, что введено в ячейке
string statusName = (string)dataGridView.CurrentRow.Cells[1].Value;
//если в ячейке есть текст (строка непустая)
if (!string.IsNullOrEmpty(statusName))
{
//если есть id, то надо обновить
if (dataGridView.CurrentRow.Cells[0].Value != null)
{
_storage.Update(new StatusBindingModel()
{
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
//если нет id, значит надо создать запись
else
{
_storage.Insert(new StatusBindingModel()
{
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
}
//если строка пустая
else
{
MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}