using ProjectFamilyBudget.Entities; using ProjectFamilyBudget.Entities.Enums; using ProjectFamilyBudget.Repositories; 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; using Unity; namespace ProjectFamilyBudget.Forms { public partial class FormExpense : Form { private readonly IExpense _expense; private int? _expenseId; public int Id { set { try { var expense = _expense.ReadExpenseById(value); if (expense == null) { throw new InvalidDataException(nameof(expense)); } foreach (IncomeExpenseType elem in Enum.GetValues(typeof(IncomeExpenseType))) { if ((elem & expense.ExpenseType) != 0) { checkedListBoxType.SetItemChecked(checkedListBoxType.Items.IndexOf( elem), true); } } textBoxName.Text = expense.Name; textBoxCategory.Text = expense.ExpenseCategory; _expenseId = value; } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при получени данных", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } public FormExpense(IExpense expense) { InitializeComponent(); _expense = expense ?? throw new ArgumentNullException(nameof(expense)); foreach (var elem in Enum.GetValues(typeof(IncomeExpenseType))) { checkedListBoxType.Items.Add(elem); } } private void buttonSave_Click(object sender, EventArgs e) { try { if (string.IsNullOrWhiteSpace(textBoxName.Text) || string.IsNullOrWhiteSpace(textBoxCategory.Text) || checkedListBoxType.CheckedItems.Count == 0) { throw new Exception("Имеются незаполненные поля"); } if (_expenseId.HasValue) { _expense.UpdateExpense(CreateExpense(_expenseId.Value)); } else { _expense.CreateExpense(CreateExpense(0)); } Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void buttonCansel_Click(object sender, EventArgs e) => Close(); private Expense CreateExpense(int id) { IncomeExpenseType expenseType = IncomeExpenseType.None; foreach (var elem in checkedListBoxType.CheckedItems) { expenseType |= (IncomeExpenseType)elem; } return Expense.CreateEntity(id, expenseType, textBoxName.Text, textBoxCategory.Text); } } }