MainWindow.xaml.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using Microsoft.EntityFrameworkCore;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Windows.Controls;
  10. using System.Windows.Data;
  11. using System.Windows.Documents;
  12. using System.Windows.Input;
  13. using System.Windows.Media;
  14. using System.Windows.Media.Imaging;
  15. using System.Windows.Navigation;
  16. using System.Windows.Shapes;
  17. namespace BookStore1
  18. {
  19. public partial class MainWindow : Window
  20. {
  21. private BookStoreContext _context;
  22. public MainWindow()
  23. {
  24. InitializeComponent();
  25. _context = new BookStoreContext();
  26. Load();
  27. }
  28. private void Load()
  29. {
  30. BooksGrid.ItemsSource = _context.Books.ToList();
  31. }
  32. private void BtnInsert_Click(object sender, RoutedEventArgs e)
  33. {
  34. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  35. {
  36. return;
  37. }
  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. {
  55. return;
  56. }
  57. selectedBook.Name = TbName.Text;
  58. selectedBook.Price = price;
  59. selectedBook.Author = TbAuthor.Text;
  60. selectedBook.Category = TbCategory.Text;
  61. _context.SaveChanges();
  62. Load();
  63. }
  64. }
  65. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  66. {
  67. if (BooksGrid.SelectedItem is Book selectedBook)
  68. {
  69. _context.Books.Remove(selectedBook);
  70. _context.SaveChanges();
  71. Load();
  72. }
  73. }
  74. private void BooksGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  75. {
  76. if (BooksGrid.SelectedItem is Book selectedBook)
  77. {
  78. TbName.Text = selectedBook.Name;
  79. TbPrice.Text = selectedBook.Price.ToString();
  80. TbAuthor.Text = selectedBook.Author;
  81. TbCategory.Text = selectedBook.Category;
  82. }
  83. }
  84. }
  85. }