In the interest of others, here is a solution that I came up with, but I would like to hear the best.
I added an extra, mutable column to the DataTable called SORT_ORDER, which is used only for sorting.
When the user clicks on the sorted column, I copy the values ββand value type from the selected column to the SORT_ORDER column, and then sort by SORT_ORDER. Since SORT_ORDER is not displayed and cannot be changed, the sort order is not changed even if the user edits the selected column. The event handler is as follows:
private void MyDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { dirtyCellListenerEnabled = false; SORT_ORDER.ValueType = MyDataGridView.Columns[e.ColumnIndex].ValueType; foreach(DataGridViewRow r in MyDataGridView.Rows) { r.Cells[SORT_ORDER.Index].Value = r.Cells[e.ColumnIndex].Value; } switch(MyDataGridView.SortOrder) { case System.Windows.Forms.SortOrder.None: MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Ascending); break; case System.Windows.Forms.SortOrder.Ascending: MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Descending); break; case System.Windows.Forms.SortOrder.Descending: MyDataGridView.Sort(SORT_ORDER, ListSortDirection.Ascending); break; } dirtyCellListenerEnabled = true; }
Please note that I had to disconnect and re-enable my listener so that my code would not treat the update of the sort column as a real change.
Before proceeding with this solution, I also tried adding a sort column to the DataGridView, but it does not work because the DataGridView cannot sort a column that does not exist in its data source.
I'm sure there are other tweaks that I could do, for example, pause updates when filling out SORT_ORDER and display the sort glyph in the selected column.
didge source share