84 lines
2.8 KiB
C#

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;
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));
}
textBoxName.Text = expense.Name;
comboBoxExpenseType.SelectedItem = expense.ExpenseType;
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));
comboBoxExpenseType.DataSource = Enum.GetValues(typeof(IncomeExpenseType));
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxName.Text)
||
string.IsNullOrWhiteSpace(textBoxCategory.Text) || (comboBoxExpenseType.SelectedIndex < 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) => Expense.CreateEntity(id, (IncomeExpenseType)comboBoxExpenseType.SelectedItem!
, textBoxName.Text, textBoxCategory.Text);
}
}