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

103 lines
3.7 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) {
var name = dataGridView.Rows[e.RowIndex].Cells[0].Value?.ToString()
?? throw new Exception("Не заполнено название роли");
_logic.Update(new RoleBindingModel { Id = Convert.ToInt32(dataGridView.Rows[e.RowIndex].Cells[1].Value), Name = name });
2024-10-22 19:42:03 +04:00
}
else
{
var name = dataGridView.Rows[e.RowIndex].Cells[0].Value?.ToString()
?? throw new Exception("Не заполнено название роли");
_logic.Create(new RoleBindingModel { Id = 0, Name = name });
2024-10-22 19:42:03 +04:00
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 (row.IsNewRow)
continue;
if (row.Cells[1].Value != null && !_logic.Delete(new RoleBindingModel { Id = Convert.ToInt32(row.Cells[1].Value) }))
throw new Exception($"Ошибка удаления строки: {row.Cells[0].Value}");
2024-10-22 19:42:03 +04:00
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;
2024-10-22 19:42:03 +04:00
DeleteRows(dataGridView.SelectedRows);
}
}
}