MainWindow.xaml.cs 2.7 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 BookStokeSQL
  16. {
  17. /// <summary>
  18. /// Логика взаимодействия для MainWindow.xaml
  19. /// </summary>
  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. if (context_.Books.ToList().Count != 0)
  32. BooksGrid.ItemsSource = context_.Books.ToList();
  33. }
  34. private void BtnInsert_CLick(object sender, RoutedEventArgs e)
  35. {
  36. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  37. {
  38. return;
  39. }
  40. Book book = new Book()
  41. {
  42. Name = TbName.Text,
  43. Price = price,
  44. Author = TbAuthor.Text,
  45. Category = TbCategory.Text,
  46. };
  47. context_.Books.Add(book);
  48. context_.SaveChanges();
  49. Load();
  50. }
  51. private void BtnUpdate_Click(object sender, RoutedEventArgs e)
  52. {
  53. if (BooksGrid.SelectedItem is Book selectedBook)
  54. {
  55. if (!decimal.TryParse(TbPrice.Text, out decimal price))
  56. {
  57. return;
  58. }
  59. selectedBook.Name = TbName.Text;
  60. selectedBook.Price = price;
  61. selectedBook.Author = TbAuthor.Text;
  62. selectedBook.Category = TbCategory.Text;
  63. context_.SaveChanges();
  64. Load();
  65. }
  66. }
  67. private void BtnDelete_Click(object sender, RoutedEventArgs e)
  68. {
  69. if (BooksGrid.SelectedItem is Book selectedBook)
  70. {
  71. context_.Books.Remove(selectedBook);
  72. context_.SaveChanges();
  73. Load();
  74. }
  75. }
  76. private void BooksGrid_SelectionChanged(object sender, RoutedEventArgs e)
  77. {
  78. if (BooksGrid.SelectedItem is Book selectedBook)
  79. {
  80. TbName.Text = selectedBook.Name;
  81. TbPrice.Text = selectedBook.Price.ToString();
  82. TbAuthor.Text = selectedBook.Author;
  83. TbCategory.Text = selectedBook.Category;
  84. }
  85. }
  86. }
  87. }