Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Datagridview with Multisort

5.00/5 (3 votes)
4 Mar 2018CPOL 9.9K   7  
Here is a simple way to sort the datagridview by Multi-Columns

Introduction

This tip shows you how to sort the datagridview by any column.

Use the ColumnHeaderMouseClick event to sort a BindingSource.

Image 1

Using the Code

VB.NET
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)