Introduction
This tip shows you how to sort the datagridview
by any column.
Use the ColumnHeaderMouseClick
event to sort a BindingSource
.
Using the Code
If Control.ModifierKeys = Keys.Control Then
If dataSource.Sort.Contains(DataGridView1.Columns(e.ColumnIndex).Name) Then
If dataSource.Sort.Contains(DataGridView1.Columns(e.ColumnIndex).Name + " ASC") Then
dataSource.Sort = dataSource.Sort.Replace(DataGridView1.Columns(e.ColumnIndex).Name + _
" ASC", DataGridView1.Columns(e.ColumnIndex).Name + " DESC")
Else
dataSource.Sort = dataSource.Sort.Replace(DataGridView1.Columns(e.ColumnIndex).Name + _
" DESC", DataGridView1.Columns(e.ColumnIndex).Name + " ASC")
End If
Else
dataSource.Sort += ", " & DataGridView1.Columns(e.ColumnIndex).Name + " ASC"
End If
Dim allSort() As String = Split(dataSource.Sort, ", ")
For Each s As String In allSort
Dim iSortOrder() As String = Split(s, " ")
Dim cName As String = s.Replace(" " + iSortOrder(iSortOrder.Length - 1), "")
Select Case iSortOrder(iSortOrder.Length - 1)
Case "ASC"
DataGridView1.Columns(cName).HeaderCell.SortGlyphDirection = SortOrder.Ascending
Case "DESC"
DataGridView1.Columns(cName).HeaderCell.SortGlyphDirection = SortOrder.Descending
End Select
Next
Else
If dataSource.Sort.Contains(DataGridView1.Columns(e.ColumnIndex).Name + " DESC") Then
dataSource.Sort = DataGridView1.Columns(e.ColumnIndex).Name + " ASC"
Else
dataSource.Sort = DataGridView1.Columns(e.ColumnIndex).Name + " DESC"
End If
End If