Ryan Peschel
Ryan Peschel

Reputation: 11996

How to prevent selection order influencing which row comes first in a DataGridView?

I have a DataGridView on a form and here's an example of its contents:

Cat  | Boy
Dog  | Girl
Crow | Boy
Bird | Boy

I have MultiSelect enabled and if I start my selection at the fourth row (Bird) and drag to the first row (Cat), then in the SelectedRows collection, the first item is Cat (because the editing indicator is there). This is good.

However, if I start my selection at the first row (Cat) and drag down to the fourth row (Bird), then the editing indicator is at Bird and as a result, the first row in the collection is that of Bird. The second item is Crow, and it proceeds upwards accordingly.

Is there any way to change the behavior so that the first item in the collection is always the first row selected (from top to bottom) and then proceeds downwards accordingly, ignoring user selection direction?

I tried changing RowHeadersVisible to false and while that did remove the black indicator on the left, the problem still persists.

Thanks.

Upvotes: 1

Views: 122

Answers (1)

Ryan Peschel
Ryan Peschel

Reputation: 11996

var orderedRows = dataGridView.SelectedRows.Cast<DataGridViewRow>().OrderBy(row => row.Index);

Upvotes: 1

Related Questions