using PortalAccountsContracts.BindingModels; using PortalAccountsContracts.BusinessLogicsContracts; namespace PortalAccountsView { public partial class FormInterests : Form { private readonly IInterestLogic _logic; private bool dataLoading = false; public FormInterests(IInterestLogic logic) { InitializeComponent(); _logic = logic; } private void FormInterestss_Load(object sender, EventArgs e) { LoadData(); } private void LoadData() { dataLoading = true; try { var list = _logic.ReadList(null); if (list != null) { foreach (var interest in list) { int rowIndex = dataGridView.Rows.Add(); dataGridView.Rows[rowIndex].Cells[0].Value = interest.Name; dataGridView.Rows[rowIndex].Cells[1].Value = interest.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 InterestBindingModel { 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 InterestBindingModel { Id = 0, Name = name }); var list = _logic.ReadList(null) ?? throw new Exception("Не удалось получить список интересов"); int newInterestsId = list.Last().Id; dataGridView.Rows[e.RowIndex].Cells[1].Value = newInterestsId; } } 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 InterestBindingModel { 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); } } }