I
I
iviner2015-06-05 12:07:14
SQL
iviner, 2015-06-05 12:07:14

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);
            }
        }

Book is a table in the DB and BookGD is a datagrid that displays books from the Book table. HomeLibraryDatabase - the actual name of the database.
When a row is selected and the "Delete" button is clicked, the Unable to cast object of type 'System.Data.DataRowView' to type 'HomeLibrary.Book' error occurs.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artyom, 2015-06-05
@artem_b89

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

R
Roman, 2015-06-05
@yarosroman

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 question

Ask a Question

731 491 924 answers to any question