Search code examples
c#wpfvb.net.net-coredatagrid

What is the best way to get values from the currently selected row in a WPF datagrid?


We have recently decided to recreate our Winforms app in WPF. In Winforms I get the values of the current row like so:

Dim supplier As String = tbl_outstandingpos.CurrentRow.Cells("Supplier").Value

In WPF the best way I could find so far is

DataRowView row = dataGrid.SelectedItem as DataRowView;
MessageBox.Show(row.Row.ItemArray[1].ToString());

Which doesn't work for me as I don't want to get the column by index but by name.

I have read a lot about MVVM, I still don't see that giving the results I am looking for.

I want the user to select a row, then there are labels/textblocks that are filled with the values from that row(Some of which are in hidden columns in the DataGrid)

I am using C# for the new app, we used VB for the winforms one.


Solution

  • Given that the DataGrid.ItemsSource is a DataTable the SelectedItem will be an DataRowView instance. You can access the selected row by column name by using the appropriate indexer property:

    C#

    // Get the value of the selected row's 'LastName' column
    var columnValue = (this.MyDataGrid.SelectedItem as DataRowView)["LastName"];
    this.MyTextBlock.Text = columnValue;
    

    XAML

    <DataGrid x:Name="DataGrid" 
              ItemsSource="{Binding DataTable}" />
    
    <!-- A TextBlock to display the content of the selected rows 'LastName'  column -->
    <TextBlock x:Name="MyTextBlock" 
               Text="{Binding ElementName=DataGrid, Path=SelectedItem[LastName]}"/>
    

    You may consider to add a dedicated SelectedRow property of type DataRowView to your view model instead of having your controls bind directly to the DataGrid.SelectedItem property.