PIbd-32_Artamonova_T.V._COP_2/UniversityView/FormHandbooks.cs

111 lines
4.0 KiB
C#
Raw Normal View History

2023-10-28 09:06:35 +04:00
using System.ComponentModel;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicsContracts;
namespace UniversityView
{
public partial class FormHandbooks : Form
{
private readonly IDirectionLogic _logic;
BindingList<DirectionBindingModel> _list;
private int? _id;
public int Id { set { _id = value; } }
public FormHandbooks(IDirectionLogic logic)
{
InitializeComponent();
_logic = logic;
_list = new BindingList<DirectionBindingModel>();
dataGridView.AllowUserToAddRows = false;
}
private void FormHandbooks_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
2023-11-09 04:07:06 +04:00
var list = _logic.Read(null);
2023-10-28 09:06:35 +04:00
_list.Clear();
foreach (var item in list)
{
_list.Add(new DirectionBindingModel
{
Id = item.Id,
Name = item.Name,
});
}
if (_list != null)
{
dataGridView.DataSource = _list;
dataGridView.Columns[0].Visible = false;
dataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var typeName = (string)dataGridView.CurrentRow.Cells[1].Value;
if (!string.IsNullOrEmpty(typeName))
{
if (dataGridView.CurrentRow.Cells[0].Value != null)
{
_logic.CreateOrUpdate(new DirectionBindingModel()
{
Id = Convert.ToInt32(dataGridView.CurrentRow.Cells[0].Value),
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
else
{
_logic.CreateOrUpdate(new DirectionBindingModel()
{
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
}
else
{
MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Insert)
{
if (dataGridView.Rows.Count == 0)
{
_list.Add(new DirectionBindingModel());
dataGridView.DataSource = new BindingList<DirectionBindingModel>(_list);
dataGridView.CurrentCell = dataGridView.Rows[0].Cells[1];
return;
}
if (dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1].Value != null)
{
_list.Add(new DirectionBindingModel());
dataGridView.DataSource = new BindingList<DirectionBindingModel>(_list);
dataGridView.CurrentCell = dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1];
return;
}
}
if (e.KeyData == Keys.Delete)
{
if (MessageBox.Show("Удалить выбранный элемент", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_logic.Delete(new DirectionBindingModel() { Id = (int)dataGridView.CurrentRow.Cells[0].Value });
LoadData();
}
}
}
}
}