Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning/Getting DataGrid Row index from button click

Tags:

c#

wpf

xaml

I'm having trouble returning which row a button was clicked from in my wpf project.

I have the following so far...

XAML -

    <DataGrid x:Name="myDataGrid" HorizontalAlignment="Left" Width="550">
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name"></DataGridTextColumn>
            <DataGridTemplateColumn Width="200">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Click="RowEvent">X</Button>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

C# -

    private void RowEvent(object sender, RoutedEventArgs e)
    {
        Button btn = sender as Button;
    }

I seem to recall that when I was using a dataGridView in Win Forms I could get the row index from e.RowIndex if I remember correctly, but I cant seem to do that this time.

Could anyone point me in the right direction?

like image 460
James Leitz Avatar asked Oct 16 '25 15:10

James Leitz


1 Answers

Just use:

DataGrid.SelectedIndex Property

... like this:

    private void RowEvent(object sender, RoutedEventArgs e)
    {
        int index = myDataGrid.SelectedIndex;
        MessageBox.Show(index.ToString());
    }
like image 107
voytek Avatar answered Oct 18 '25 04:10

voytek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!