MainWindow.xaml.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using BookStore;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Documents;
  11. using System.Windows.Input;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using System.Windows.Navigation;
  15. using System.Windows.Shapes;
  16. namespace WpfApp1
  17. {
  18. /// <summary>
  19. /// Interaction logic for MainWindow.xaml
  20. /// </summary>
  21. public partial class MainWindow : Window
  22. {
  23. private BookStoreContext _context;
  24. public MainWindow()
  25. {
  26. InitializeComponent();
  27. _context = new BookStoreContext();
  28. Load();
  29. }
  30. private void Load()
  31. {
  32. BooksGrid.ItemsSource = _context.Books.ToList();
  33. }
  34. private void BtnInsert_Click(object sender, RoutedEventArgs e)
  35. {
  36. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  37. return;
  38. Book book = new()
  39. {
  40. Name = TbName.Text,
  41. Price = price,
  42. Author = TbAuthor.Text,
  43. Category = TbCategory.Text,
  44. };
  45. _context.Books.Add(book);
  46. _context.SaveChanges();
  47. Load();
  48. }
  49. private void BtnUpdate_Click(object sender, RoutedEventArgs e)
  50. {
  51. if (BooksGrid.SelectedItem is Book selectedBook)
  52. {
  53. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  54. return;
  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. }