Search code examples
c#wpfdatagridwpfdatagrid

Reset DataGrid.SelectedIndex after user has selected another


In the UI I'm working with, in a DataGrid, there are cases where the user might select a different row, but after a dialog interaction, the old row needs to be shown as being selected once again. If I simply try

BundleQueueDG.SelectedIndex = currentBundleIndex;

that does not do anything and in fact, once the SelectionChanged method exits, it changes to the new value. What is the best way to "re-select" the previously-selected row?


Solution

  • Try setting the SelectedItem property. Preserve what was selected before and set the SelectedItem with what was previously selected in your event. Something like this:

    private void DgDataGrid_OnSelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            int newIndex = (sender as DataGrid).SelectedIndex / 2;
            if (Convert.ToInt32(newIndex) >= 1)
                (sender as DataGrid).SelectedItem = previous;
            else
            {
                previous = (sender as DataGrid).CurrentItem;
            }
        }