using AccountsContracts.BindingModels; using AccountsContracts.BusinessLogicContracts; 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 AccountsApp { public partial class FormInterests : Form { private readonly IInterestLogic _logic; private bool loading = false; public FormInterests(IInterestLogic logic) { InitializeComponent(); _logic = logic; } private void FormInterests_Load(object sender, EventArgs e) { LoadData(); } private void LoadData() { loading = 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 { 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 InterestBindingModel { 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 InterestBindingModel { Id = 0, Name = name.ToString() }); int newInterestId = _logic.ReadList(null).ToList().Last().Id; dataGridView.Rows[e.RowIndex].Cells[1].Value = newInterestId; } } 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 InterestBindingModel { 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); } } }