84 lines
2.8 KiB
C#
Raw Normal View History

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
{
2024-11-05 17:54:04 +04:00
public partial class FormExpense : Form
{
2024-11-05 17:54:04 +04:00
private readonly IExpense _expense;
private int? _expenseId;
public int Id
{
set
{
try
{
2024-11-05 17:54:04 +04:00
var expense = _expense.ReadExpenseById(value);
if (expense == null)
{
2024-11-05 17:54:04 +04:00
throw new InvalidDataException(nameof(expense));
}
2024-11-05 17:54:04 +04:00
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;
}
}
}
2024-11-05 17:54:04 +04:00
public FormExpense(IExpense expense)
{
InitializeComponent();
2024-11-05 17:54:04 +04:00
_expense = expense ??
throw new ArgumentNullException(nameof(expense));
comboBoxExpenseType.DataSource = Enum.GetValues(typeof(IncomeExpenseType));
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
2024-11-05 17:54:04 +04:00
if (string.IsNullOrWhiteSpace(textBoxName.Text)
||
2024-11-05 17:54:04 +04:00
string.IsNullOrWhiteSpace(textBoxCategory.Text) || (comboBoxExpenseType.SelectedIndex < 0))
{
throw new Exception("Имеются незаполненные поля");
}
2024-11-05 17:54:04 +04:00
if (_expenseId.HasValue)
{
2024-11-05 17:54:04 +04:00
_expense.UpdateExpense(CreateExpense(_expenseId.Value));
}
else
{
2024-11-05 17:54:04 +04:00
_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();
2024-11-05 17:54:04 +04:00
private Expense CreateExpense(int id) => Expense.CreateEntity(id, (IncomeExpenseType)comboBoxExpenseType.SelectedItem!
, textBoxName.Text, textBoxCategory.Text);
}
}