MainWindow.xaml.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. using Microsoft.EntityFrameworkCore.SqlServer;
  16. using Microsoft.EntityFrameworkCore;
  17. namespace BookStore
  18. {
  19. 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 BthInsert_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. private void TbName_TextChanged(object sender, TextChangedEventArgs e)
  85. {
  86. }
  87. }
  88. }