MainWindow.xaml.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Linq;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. namespace WpfApp1
  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 BtnUpdate_Click(object sender, RoutedEventArgs e)
  20. {
  21. if (BooksGrid.SelectedItem is Book selectedBook)
  22. {
  23. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  24. {
  25. return;
  26. }
  27. selectedBook.Name = TbName.Text;
  28. selectedBook.Price = price;
  29. selectedBook.Author = TbAuthor.Text;
  30. selectedBook.Category = TbCategory.Text;
  31. _context.SaveChanges();
  32. Load();
  33. }
  34. }
  35. private void BookGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  36. {
  37. if (BooksGrid.SelectedItem is Book selectedBook)
  38. {
  39. TbName.Text = selectedBook.Name;
  40. TbPrice.Text = selectedBook.Price.ToString();
  41. TbAuthor.Text = selectedBook.Author;
  42. TbCategory.Text = selectedBook.Category;
  43. }
  44. }
  45. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  46. {
  47. if (BooksGrid.SelectedItem is Book selectedBook)
  48. {
  49. _context.Books.Remove(selectedBook);
  50. _context.SaveChanges();
  51. Load();
  52. }
  53. }
  54. private void BtnInsert_Click(object sender, RoutedEventArgs e)
  55. {
  56. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  57. {
  58. return;
  59. }
  60. Book book = new()
  61. {
  62. Name = TbName.Text,
  63. Price = price,
  64. Author = TbAuthor.Text,
  65. Category = TbCategory.Text,
  66. };
  67. _context.Books.Add(book);
  68. _context.SaveChanges();
  69. Load();
  70. }
  71. }
  72. }