MainWindow.xaml.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 WpfApp1
  16. {
  17. /// <summary>
  18. /// Interaction logic for MainWindow.xaml
  19. /// </summary>
  20. public partial class MainWindow : Window
  21. {
  22. private BookStoreContext _context;
  23. public MainWindow()
  24. {
  25. InitializeComponent();
  26. _context = new BookStoreContext();
  27. Load();
  28. }
  29. private void Load()
  30. {
  31. BooksGrid.ItemsSource = _context.Books.ToList();
  32. }
  33. private void BtnInsert_Click(object sender, RoutedEventArgs e)
  34. {
  35. if(!decimal.TryParse(TbPrice.Text, out decimal price))
  36. return;
  37. Book book = new()
  38. {
  39. Name = TbName.Text,
  40. Price = price,
  41. Author = TbAuthor.Text,
  42. Category = TbCategory.Text,
  43. };
  44. _context.Books.Add(book);
  45. _context.SaveChanges();
  46. Load();
  47. }
  48. private void BtnUpdate_Click(object sender, RoutedEventArgs e)
  49. {
  50. if(BooksGrid.SelectedItem is Book selectedBook)
  51. {
  52. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  53. return;
  54. selectedBook.Name = TbName.Text;
  55. selectedBook.Price = price;
  56. selectedBook.Author = TbAuthor.Text;
  57. selectedBook.Category = TbCategory.Text;
  58. _context.SaveChanges();
  59. Load();
  60. }
  61. }
  62. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  63. {
  64. if(BooksGrid.SelectedItem is Book selectedBook)
  65. {
  66. _context.Books.Remove(selectedBook);
  67. _context.SaveChanges();
  68. Load();
  69. }
  70. }
  71. private void BooksGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  72. {
  73. if(BooksGrid.SelectedItem is Book selectedBook)
  74. {
  75. TbName.Text = selectedBook.Name;
  76. TbPrice.Text = selectedBook.Price.ToString();
  77. TbAuthor.Text = selectedBook.Author;
  78. TbCategory.Text = selectedBook.Category;
  79. }
  80. }
  81. }
  82. }