简体   繁体   中英

get data from datagrid on button click in WPF application

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?

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;
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM