Hi, @Kamyab Faghih.
This is not a good example of what might cause the selectedRow
and index
to be incorrect. You could check and correct dgrdMain.SelectedIndex
and dgrdMain.SelectedValue
in the DataGrid's Selected
event.
However, if your Button is in each row, you could find a different way to get the selectedRow
and index
. Adjust the code provided in the comments:
MainWindow.xaml
<Grid>
<DataGrid x:Name="dgrdMain" AutoGenerateColumns="False" CanUserAddRows="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Binding="{Binding Id}" ></DataGridTextColumn>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"></DataGridTextColumn>
<DataGridTemplateColumn Header="Option">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Button Height="50" Width="100" Content="Clike Me" Click="ModifyProductSellPrices"></Button>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
MainWindow.xaml.cs
private void ModifyProductSellPrices(object sender, RoutedEventArgs e)
{
// Get the DataContext of the button, which should be the corresponding data row
var button = sender as Button;
var selectedRow = button.DataContext as ProductSize;
// Find the index of the row in the DataGrid
int index = dgrdMain.Items.IndexOf(selectedRow);
// Output to verify
if (selectedRow != null && index != -1)
{
MessageBox.Show(selectedRow?.ToString() + "\n" + index.ToString());
}
else
{
MessageBox.Show("Unselected Item");
}
// Correct DataGrid's SelectedItem and SelectedIndex
dgrdMain.SelectedIndex = index;
dgrdMain.SelectedValue = selectedRow;
}
If you still cannot get the correct result, you could narrow down the scope of the problem: Is there an error between the data bound to each row and the data bound to DataGrid.ItemSource.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.