I have a databound DataGridView in a Win Forms app which the user may have sorted by a column. The problem is this: after the user leaves a row after editing a cell in the sorted column, the row is immediately re-sorted.
This is very disorienting for users and makes editing groups of rows together impossible.
The solution I’m looking for will effectively disable automatic re-sorting after an initial sort and then only sort again when the user requests it.
For the benefit of others, here is the solution I came up with, but I’d love to hear a better one.
I added an additional, non-persistent column to the DataTable called SORT_ORDER which is used only for sorting.
When the user clicks a column to sort, I copy the values and value type from the selected column to the SORT_ORDER column and then sort on SORT_ORDER. Since the SORT_ORDER is not visible and can’t be edited, the sort order does not change even if the user edits the selected column. The event handler looks like this:
Note that I had to disable and re-enable my cell listener so that my code doesn’t treat the sort column update as a real change.
Before arriving at this solution, I had also tried adding the sort column to the DataGridView, but it doesn’t work because the DataGridView can’t sort on a column that doesn’t exist in its data source.
I’m sure there are some other tweaks I could do, too, like suspending updates while populating the SORT_ORDER and displaying the sort glyph on the selected column.