Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected row item in DataGrid WPF

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.

like image 694
Mike Avatar asked Oct 12 '10 10:10

Mike


People also ask

How to get selected item from grid in WPF?

<DataGrid. Columns> <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>


2 Answers

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> 
like image 181
Alex McBride Avatar answered Sep 20 '22 08:09

Alex McBride


If you're using the MVVM pattern you can bind a SelectedRecord property of your VM with SelectedItem of the DataGrid, this way you always have the SelectedValue in you VM. Otherwise you should use the SelectedIndex property of the DataGrid.

like image 28
ema Avatar answered Sep 20 '22 08:09

ema