MainWindow.xaml.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using Bookstore;
  2. using MongoDB.Bson;
  3. using MongoDB.Driver;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Controls;
  11. using System.Windows.Data;
  12. using System.Windows.Documents;
  13. using System.Windows.Input;
  14. using System.Windows.Media;
  15. using System.Windows.Media.Imaging;
  16. using System.Windows.Navigation;
  17. using System.Windows.Shapes;
  18. namespace BookStore
  19. {
  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.GetCollection<Book>("Book").Find(new BsonDocument()).ToList();
  32. }
  33. private void BtnUpdate_Click(object sender, RoutedEventArgs e)
  34. {
  35. if (BooksGrid.SelectedItem is Book selectedBook)
  36. {
  37. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  38. {
  39. return;
  40. }
  41. selectedBook.Name = TbName.Text;
  42. selectedBook.Price = price;
  43. selectedBook.Author = TbAuthor.Text;
  44. selectedBook.Category = TbCategory.Text;
  45. _context.GetCollection<Book>("Book").ReplaceOne(x => x.Id == selectedBook.Id, selectedBook);
  46. Load();
  47. }
  48. }
  49. private void BookGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  50. {
  51. if (BooksGrid.SelectedItem is Book selectedBook)
  52. {
  53. TbName.Text = selectedBook.Name;
  54. TbPrice.Text = selectedBook.Price.ToString();
  55. TbAuthor.Text = selectedBook.Author;
  56. TbCategory.Text = selectedBook.Category;
  57. }
  58. }
  59. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  60. {
  61. if (BooksGrid.SelectedItem is Book selectedBook)
  62. {
  63. _context.GetCollection<Book>("Book").DeleteOne(x => x.Id == selectedBook.Id);
  64. Load();
  65. }
  66. }
  67. private void BtnInsert_Click(object sender, RoutedEventArgs e)
  68. {
  69. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  70. {
  71. return;
  72. }
  73. Book book = new()
  74. {
  75. Name = TbName.Text,
  76. Price = price,
  77. Author = TbAuthor.Text,
  78. Category = TbCategory.Text,
  79. };
  80. _context.GetCollection<Book>("Book").InsertOne(book);
  81. Load();
  82. }
  83. }
  84. }