views:

454

answers:

1

I have a datagridview that may or may not have rows selected when the user sorts it by clicking on a column header. If there are rows selected there isn't a problem, but if there are 0 selected rows then the sort selects a row automatically (the selection is consistant but I'm not wure what the criteria is). How can I prevent this behavior from happening.

If it's relevant, the DGV is not databound and has full row select enabled.

+3  A: 

Handle the Sorted event of the DataGridView:

this.dataGridView1.Sorted += new System.EventHandler(dataGridView1_Sorted);

void dataGridView1_Sorted(object sender, System.EventArgs e)
{
    dataGridView1.ClearSelection();
}
Joshua Drake
That would also clear existing user selections which I want to be preserved. There doesn't appear to be an event that fires before the sort is carried out like there is when a form is closed (FormClosing and FormClosed) that I could use to check the state to determine if the selection should be cleared afterwards.
Dan Neely
The CellMouseDown event fires before the sort and can be used to check the selection state. The more likely looking ColumnHeaderClick event fires after the sort and is useless.
Dan Neely
The additional code needed is:bool selectionsMade = false; private void DataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if ((e.Button == MouseButtons.Left) } }
Dan Neely
Did the additional handling code you mention solve your issue?
Joshua Drake
Yes, combining it with your sorted event did solve the issue.
Dan Neely