Answer the question
In order to leave comments, you need to log in
How to get value from datagrid in WPF?
Good afternoon.
How to actually get the value from the datagrid? I want to take the Id from the selected row and assign it to an int variable so that I can then pass it to the delete request. The base Id is also of type int. The task itself is to create something like a home library so that the datagrid displays the books.
private void ButtonDeleteBook_Click(object sender, RoutedEventArgs e)
{
HomeLibraryDatabaseEntities context = new HomeLibraryDatabaseEntities();
try
{
int selectedId = ((Book)BookDG.SelectedItem).IdBook;
Book selectedBook = context.Book.Where(o => o.IdBook == selectedId ).Select(o => o).First();
context.Book.Remove(selectedBook);
context.SaveChanges();
MessageBox.Show("Объект успешно удален");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Answer the question
In order to leave comments, you need to log in
In general it is strange... How is the grid data source configured?
So?
those. interested in the type of the collection and the type of the elements of the collection
first,
int selected = ((Book)BookDG.SelectedItem)
context.Book.Remove(selectedBook);
context.SaveChanges();
MVVM and bindings will help you, just make a model, in it a property, for example, Selected, and write in the DataGrid, SelectedItem={Binding Selected, Mode=TwoWay}
and you can write
context.Book.Remove(Selected);
context.SaveChanges();
I recommend SimpleMVVM, simple, for small projects
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question