Get selected row item in DataGrid WPF

Mike B. picture Mike B. · Oct 12, 2010 · Viewed 218.6k times · Source

I have a DataGrid, bound to Database table, I need to get the content of selected row in DataGrid, for example, I want to show in MessageBox content of selected row.

Example of DataGrid:

enter image description here

So, if I select the second row, my MessageBox has to show something like: 646 Jim Biology.

Answer

Alex McBride picture Alex McBride · Oct 12, 2010

You can use the SelectedItem property to get the currently selected object, which you can then cast into the correct type. For instance, if your DataGrid is bound to a collection of Customer objects you could do this:

Customer customer = (Customer)myDataGrid.SelectedItem;

Alternatively you can bind SelectedItem to your source class or ViewModel.

<Grid DataContext="MyViewModel">
    <DataGrid ItemsSource="{Binding Path=Customers}"
              SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>