MainWindow.xaml.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Linq;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. namespace BookStore
  5. {
  6. public partial class MainWindow : Window
  7. {
  8. private BookStoreContext _context;
  9. public MainWindow()
  10. {
  11. InitializeComponent();
  12. _context = new BookStoreContext();
  13. Load();
  14. }
  15. private void Load()
  16. {
  17. BooksGrid.ItemsSource = _context.Books.ToList();
  18. }
  19. private void BtnInsert_Click(object sender, RoutedEventArgs e)
  20. {
  21. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  22. {
  23. return;
  24. }
  25. Book book = new()
  26. {
  27. Name = TbName.Text,
  28. Price = price,
  29. Autor = TbAutor.Text,
  30. Category = TbCategory.Text,
  31. };
  32. _context.Books.Add(book);
  33. _context.SaveChanges();
  34. Load();
  35. }
  36. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  37. {
  38. if (BooksGrid.SelectedItem is Book selectedBook)
  39. {
  40. _context.Books.Remove(selectedBook);
  41. _context.SaveChanges();
  42. Load();
  43. }
  44. }
  45. private void BooksGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  46. {
  47. if (BooksGrid.SelectedItem is Book selectedBook)
  48. {
  49. TbName.Text = selectedBook.Name;
  50. TbPrice.Text = selectedBook.Price.ToString();
  51. TbAutor.Text = selectedBook.Autor;
  52. TbCategory.Text = selectedBook.Category;
  53. }
  54. }
  55. private void BtnUpdate_Click(object sender, RoutedEventArgs e)
  56. {
  57. if (BooksGrid.SelectedItem is Book selectedBook)
  58. {
  59. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  60. {
  61. return;
  62. }
  63. selectedBook.Name = TbName.Text;
  64. selectedBook.Price = price;
  65. selectedBook.Autor = TbAutor.Text;
  66. selectedBook.Category = TbCategory.Text;
  67. _context.SaveChanges();
  68. Load();
  69. }
  70. }
  71. }
  72. }