using AccountContracts.BindingModels; using AccountContracts.BusinessLogicsContracts; 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 AccountsView { public partial class FormRoles : Form { private readonly IRoleLogic _logic; private bool loading = false; public FormRoles(IRoleLogic logic) { InitializeComponent(); _logic = logic; } private void FormRoles_Load(object sender, EventArgs e) { LoadData(); } private void LoadData() { loading = true; try { var list = _logic.ReadList(); if (list != null) { foreach (var role in list) { int rowIndex = dataGridView.Rows.Add(); dataGridView.Rows[rowIndex].Cells[0].Value = role.RoleName; dataGridView.Rows[rowIndex].Cells[1].Value = role.Id; } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { loading = false; } } private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) { if (loading || 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), RoleName = name.ToString() }); } else { var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value; if (name is null) return; _logic.Create(new RoleBindingModel { Id = 0, RoleName = name.ToString() }); int newRoleId = _logic.ReadList().ToList().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); } } }