MainWindow.xaml.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Linq;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using Microsoft.EntityFrameworkCore;
  5. using Microsoft.EntityFrameworkCore.SqlServer;
  6. namespace BookStore_2._0
  7. {
  8. /// <summary>
  9. /// Interaction logic for MainWindow.xaml
  10. /// </summary>
  11. public partial class MainWindow : Window
  12. {
  13. private BookStoreContext _context;
  14. public MainWindow()
  15. {
  16. InitializeComponent();
  17. _context = new BookStoreContext();
  18. Load();
  19. }
  20. private void Load()
  21. {
  22. BooksGrid.ItemsSource = _context.Books.ToList();
  23. }
  24. private void BtnInsert_Click(object sender, RoutedEventArgs e)
  25. {
  26. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  27. {
  28. return;
  29. }
  30. Book book = new()
  31. {
  32. Name = TbName.Text,
  33. Price = price,
  34. Author = TbAuthor.Text,
  35. Category = TbCategory.Text,
  36. };
  37. _context.Books.Add(book);
  38. _context.SaveChanges();
  39. Load();
  40. }
  41. private void BtnUpdate_Click(object sender, RoutedEventArgs e)
  42. {
  43. if (BooksGrid.SelectedItem is Book selectedBook)
  44. {
  45. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  46. {
  47. return;
  48. }
  49. selectedBook.Name = TbName.Text;
  50. selectedBook.Price = price;
  51. selectedBook.Author = TbAuthor.Text;
  52. selectedBook.Category = TbCategory.Text;
  53. _context.SaveChanges();
  54. Load();
  55. }
  56. }
  57. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  58. {
  59. if (BooksGrid.SelectedItem is Book selectedBook)
  60. {
  61. _context.Books.Remove(selectedBook);
  62. _context.SaveChanges();
  63. Load();
  64. }
  65. }
  66. private void BooksGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  67. {
  68. if (BooksGrid.SelectedItem is Book selectedBook)
  69. {
  70. TbName.Text = selectedBook.Name;
  71. TbPrice.Text = selectedBook.Price.ToString();
  72. TbAuthor.Text = selectedBook.Author;
  73. TbCategory.Text = selectedBook.Category;
  74. }
  75. }
  76. }
  77. }