开发者

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?


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


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


Just handle the DataBindingComplete event of the datagridview like this:

private void datagridview1_DataBindingComplete(System.Object sender, System.Windows.Forms.DataGridViewBindingCompleteEventArgs e)

{
datagridview1.ClearSelection();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜