Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView that always has one row selected

I'm using a DGV to show a list of images with text captions as a picklist. Their must always be a one and only one selection made in the list. I can't find a way to prevent the user from clearing the selection with a control-click on the selected row.

Is there a property in the designer I'm missing that could do this?

If I have to override the behavior in the mouse click events are there other ways the user could clear the current selection that need covered as well?

Is there a third approach I could take that's less cumbersome than my second idea?

like image 878
Dan Is Fiddling By Firelight Avatar asked Mar 16 '10 12:03

Dan Is Fiddling By Firelight


1 Answers

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).

like image 59
Daniel Stutzbach Avatar answered Nov 04 '22 10:11

Daniel Stutzbach