The easiest way is to catch the SelectionChanged
event and check to see if the user has unselected all rows. If so, reselect the previously selected row. Essentially, you're intercepting their action and switching the selection back. Something like this (code untested but you will get the idea):
DataGridViewRow last_selected_row;
private void dgv_SelectionChanged(object sender, EventArgs e)
{
if (dgv.SelectedRows.Count == 0)
last_selected_row.Selected = true;
else
last_selected_row = dgv.SelectedRows[0];
}
Depending on your application, it might be better to store the row index rather than a reference to the row itself. Also be sure to initialize last_selected_row and update it if you delete any rows.
Any other controls that hook the SelectionChanged
event will need to safely handle the case that no rows are selected, in case they fire before the event that switches it back. They can just return immediately though, safe in the knowledge that SelectionChanged
will fire again momentarily.
You could also subclass DataGridView
and override the OnSelectionChanged
method. Then you could reselect the last selected row before the event fires (it will fire when you call base.OnSelectionChanged
).