KOP_Library_v5/Library/FormAuthor.cs

120 lines
3.2 KiB
C#

using Contracts.BindingModels;
using Contracts.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 Library
{
public partial class FormAuthor : Form
{
private readonly IAuthorLogic authorLogic;
BindingList<AuthorBindingModel> authorBindingList;
public FormAuthor(IAuthorLogic _authorLogic)
{
InitializeComponent();
authorLogic = _authorLogic;
authorBindingList = new BindingList<AuthorBindingModel>();
dataGridView1.AllowUserToAddRows = false;
}
private void LoadData()
{
try
{
var list1 = authorLogic.Read(null);
authorBindingList.Clear();
foreach (var item in list1)
{
authorBindingList.Add(new AuthorBindingModel
{
Id = item.Id,
FIO = item.FIO,
});
}
if (authorLogic != null)
{
dataGridView1.DataSource = authorBindingList;
dataGridView1.Columns[0].Visible = false;
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var typeName = (string)dataGridView1.CurrentRow.Cells[1].Value;
if (!string.IsNullOrEmpty(typeName))
{
if (dataGridView1.CurrentRow.Cells[0].Value != null)
{
authorLogic.CreateOrUpdate(new AuthorBindingModel()
{
Id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value),
FIO = (string)dataGridView1.CurrentRow.Cells[1].EditedFormattedValue
});
}
else
{
authorLogic.CreateOrUpdate(new AuthorBindingModel()
{
FIO = (string)dataGridView1.CurrentRow.Cells[1].EditedFormattedValue
});
}
}
else
{
MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
private void FormAuthor_Load(object sender, EventArgs e)
{
LoadData();
}
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Insert)
{
if (dataGridView1.Rows.Count == 0)
{
authorBindingList.Add(new AuthorBindingModel());
dataGridView1.DataSource = new BindingList<AuthorBindingModel>(authorBindingList);
dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[1];
return;
}
if (dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value != null)
{
authorBindingList.Add(new AuthorBindingModel());
dataGridView1.DataSource = new BindingList<AuthorBindingModel>(authorBindingList);
dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1];
return;
}
}
if (e.KeyData == Keys.Delete)
{
if (MessageBox.Show("Удалить выбранный элемент", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
authorLogic.Delete(new AuthorBindingModel() { Id = (int)dataGridView1.CurrentRow.Cells[0].Value });
LoadData();
}
}
}
}
}