MainWindow.xaml.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Linq;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. namespace BookStore
  5. {
  6. public partial class MainWindow : Window
  7. {
  8. BookStoreContext _context = new BookStoreContext();
  9. public MainWindow() { InitializeComponent(); Load(); }
  10. public void Load() { BooksGrid.ItemsSource = _context.Books.ToList(); }
  11. private void BtnInsert_Click(object sender, RoutedEventArgs e) { BIC(); }
  12. public void BIC()
  13. {
  14. if (!decimal.TryParse(TbPrice.Text, out decimal price)) { return; }
  15. Book book = new Book()
  16. {
  17. Name = TbName.Text,
  18. Price = price,
  19. Author = TbAuthor.Text,
  20. Category = TbCategory.Text
  21. };
  22. _context.Books.Add(book); _context.SaveChanges(); Load();
  23. }
  24. private void BtnUpdate_Click(object sender, RoutedEventArgs e) { BUC(); }
  25. public void BUC()
  26. {
  27. if (BooksGrid.SelectedItem is Book selectedBook)
  28. {
  29. if (!decimal.TryParse(TbPrice.Text, out decimal price)) { return; }
  30. selectedBook.Name = TbName.Text;
  31. selectedBook.Price = price;
  32. selectedBook.Author = TbAuthor.Text;
  33. selectedBook.Category = TbCategory.Text;
  34. _context.SaveChanges(); Load();
  35. }
  36. }
  37. private void BtnDelete_Click(object sender, RoutedEventArgs e) { BDC(); }
  38. public void BDC()
  39. {
  40. if (BooksGrid.SelectedItem is Book selectedBook)
  41. { _context.Books.Remove(selectedBook); _context.SaveChanges(); TbClear(); Load(); }
  42. }
  43. public void TbClear()
  44. { TbName.Text = ""; TbPrice.Text = ""; TbAuthor.Text = ""; TbCategory.Text = ""; }
  45. private void BooksGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { BGSC(); }
  46. public void BGSC()
  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. }
  57. }