I had this problem today too. I have a DataGridView
that swaps out its DataSource
(a DataTable
) regularly. I was able to finally remove the sort that the user specified when the user clicked a column-header using the following code:
If dgv.SortedColumn IsNot Nothing AndAlso dgv.DataSource IsNot Nothing Then
Dim dt_Sender As DataTable = DirectCast(dgv.DataSource, DataTable)
dt_Sender.DefaultView.Sort = dt_Sender.Columns(0).ColumnName & " ASC"
End If
This functions because I have a hidden column in my DataGridView
that's always in column-index position 0. It is an integer primary key for the underlying data that happens to be sorted on data-load.
*You may have to name your index column in the DataTable
if you haven't already (e.g., dt_Sender.Columns(0).ColumnName = "colIndex"
).
*If you use a BindingSource
object as an intermediary between your DataGridView
and your DataTable
(as many people seem to do), then you'll have to nest your DirectCast
appropriately in the second line (i.e., Dim dt_Sender As DataTable = DirectCast(dgv.DataSource, DataTable)
would change to something like: Dim dt_Sender As DataTable = DirectCast(DirectCast(dgv.DataSource, BindingSource), DataTable)
).
*Additionally, if your DataTable
happens to be populated by a SQL Server query that doesn't have an integer primary key (perhaps a GUID?), then you could alter its source query to include a new row number and then hide the new column in your DataGridView
. E.g.:
SELECT Row_Number() OVER (ORDER BY (SELECT '')) AS RowNumber, Column1, Column2, Column3
FROM SourceTable
Hopefully this solution is helpful to someone else in the future.