views:

41

answers:

2

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

Example of DataGrid:

ID Name Domain

464 Alex Math

646 Jim Biology

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

Thanks.

+1  A: 

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.

ema
I don't use MVVM, I just begin with WPF/C#/.NET.If I write «ContentDataGrid.SelectedIndex», I get index of selected row in DataGrid, and I need not index, but real value, such as «646 Jim Biology». So how can I get it?
Toucki
You should consider to use a binded object so that you can bind the SelectedItem property of the datagrid. In your case you should try to navigate to the Datagrid properties to find out if it store the selected item property.
ema
+1  A: 

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="MyDataContext">
    <DataGrid ItemsSource="{Binding Path=Customers}"
              SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>    
Fara
Thank you, the first one works great!
Toucki