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

101 lines
3.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 });
}
else
{
var name = dataGridView.Rows[e.RowIndex].Cells[0].Value?.ToString()
?? throw new Exception("Не заполнено название роли");
_logic.Create(new RoleBindingModel { Id = 0, Name = name });
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.Cells[1].Value != null && !_logic.Delete(new RoleBindingModel { Id = Convert.ToInt32(row.Cells[1].Value) }))
throw new Exception($"Ошибка удаления строки: {row.Cells[0].Value}");
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);
}
}
}