MainWindow.xaml.cs 2.5 KB

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