get data from datagrid on button click in WPF application

11,881

Based on your comment you should try this then (the DataGrid is named dataGrid in XAML):

private void Button1_Click(object sender, RoutedEventArgs e)
{
    // If the grid is populated via a collection binding the SelectedItem will
    // not be a DataGridRow, but an item from the collection. You need to cast
    //  as necessary. (Of course this can be null if nothing is selected)
    var row = (DataGridRow)dataGrid.SelectedItem;
}

Could use the Tag (Edit: If you use a CheckBoxColumn you can use the styles to do this, if you have trouble with that i could give an example):

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Click="Button1_Click"
                    Tag="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
private void Button1_Click(object sender, RoutedEventArgs e)
{
    var button = (FrameworkElement)sender;
    var row = (DataGridRow)button.Tag;
    //...
}
Share:
11,881
alice7
Author by

alice7

Updated on June 05, 2022

Comments

  • alice7
    alice7 almost 2 years

    I have a datagrid which consists of a checkbox and couple of columns. When the customer clicks the checkbox I am firing grid selectionchanged event which displays some data from selectedrow to the label. But I need that selected row data when I click a button as well.

    Is there any good way to retrieve that?

  • alice7
    alice7 almost 13 years
    Sorry H.B the button is not part of the grid. It is separate down.
  • alice7
    alice7 almost 13 years
    Actually datagrid.selecteditem is what I wanted and that did the trick I guess.
  • BillJam
    BillJam almost 7 years
    I couldn't get this to work but just calling dataGrid.SelectedIndex does work since clicking the button also selects the row. However, the button is part of the grid in my case. But if you have the button outside the grid, I assume you must have also selected an item in the grid so it should still work.