MainWindow.xaml.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. Author = TbAuthor.Text,
  30. Category = TbCategory.Text,
  31. };
  32. _context.Books.Add(book);
  33. _context.SaveChanges();
  34. Load();
  35. }
  36. private void BtnUpdate_Click(object sender, RoutedEventArgs e)
  37. {
  38. if (BooksGrid.SelectedItem is Book selectedBook)
  39. {
  40. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  41. {
  42. return;
  43. }
  44. selectedBook.Name = TbName.Text;
  45. selectedBook.Price = price;
  46. selectedBook.Author = TbAuthor.Text;
  47. selectedBook.Category = TbCategory.Text;
  48. _context.SaveChanges();
  49. Load();
  50. }
  51. }
  52. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  53. {
  54. if (BooksGrid.SelectedItem is Book selectedBook)
  55. {
  56. _context.Books.Remove(selectedBook);
  57. _context.SaveChanges();
  58. Load();
  59. }
  60. }
  61. private void BooksGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  62. {
  63. if (BooksGrid.SelectedItem is Book selectedBook)
  64. {
  65. TbName.Text = selectedBook.Name;
  66. TbPrice.Text = selectedBook.Price.ToString();
  67. TbAuthor.Text = selectedBook.Author;
  68. TbCategory.Text = selectedBook.Category;
  69. }
  70. }
  71. }
  72. }