MainWindow.xaml.cs 2.5 KB

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