PIbd-31_Rodionov.I.A._COP_28/COP/PortalAccountsView/FormRoles.cs

100 lines
3.5 KiB
C#
Raw Normal View History

2024-10-22 19:42:03 +04:00
using PortalAccountsContracts.BindingModels;
using PortalAccountsContracts.BusinessLogicsContracts;
namespace PortalAccountsView
{
public partial class FormRoles : Form
{
private readonly IRoleLogic _logic;
private bool dataLoading = false;
public FormRoles(IRoleLogic logic)
{
InitializeComponent();
_logic = logic;
}
private void FormRoles_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
dataLoading = true;
try
{
var list = _logic.ReadList(null);
if (list != null)
{
foreach (var role in list)
{
int rowIndex = dataGridView.Rows.Add();
dataGridView.Rows[rowIndex].Cells[0].Value = role.Name;
dataGridView.Rows[rowIndex].Cells[1].Value = role.Id;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
dataLoading = false;
}
}
private void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataLoading || e.RowIndex < 0 || e.ColumnIndex != 0)
return;
if (dataGridView.Rows[e.RowIndex].Cells[1].Value != null && !string.IsNullOrEmpty(dataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()))
{
var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (name is null) return;
_logic.Update(new RoleBindingModel { Id = Convert.ToInt32(dataGridView.Rows[e.RowIndex].Cells[1].Value), Name = name.ToString() });
}
else
{
var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (name is null)
return;
_logic.Create(new RoleBindingModel { Id = 0, Name = name.ToString() });
var list = _logic.ReadList(null) ?? throw new Exception("Не удалось получить список ролей");
int newRoleId = list.Last().Id;
dataGridView.Rows[e.RowIndex].Cells[1].Value = newRoleId;
}
}
private void DataGridView_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Insert:
dataGridView.Rows.Add();
break;
}
}
private void DeleteRows(DataGridViewSelectedRowCollection rows)
{
for (int i = 0; i < rows.Count; i++)
{
DataGridViewRow row = rows[i];
if (!_logic.Delete(new RoleBindingModel { Id = Convert.ToInt32(row.Cells[1].Value) })) continue;
dataGridView.Rows.Remove(row);
}
}
private void DataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
e.Cancel = true;
if (dataGridView.SelectedRows == null) return;
if (MessageBox.Show("Удалить записи?", "Подтвердите действие", MessageBoxButtons.YesNo) == DialogResult.No) return;
DeleteRows(dataGridView.SelectedRows);
}
}
}