views:

283

answers:

2

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?

A: 

A DGV got a property called multiselect, if you set it to false only one cell/row can be selected at a time.

Martin S
That prevents selecting multiple rows. IT does not prevent the user from control clicking the selected row to clear the selection.
Dan Neely
+1  A: 

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

Daniel Stutzbach