MainWindow.xaml.cs 2.6 KB

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