MainWindow.xaml.cs 2.3 KB

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