.NET Tips and Tricks

Blog archive

Showing the Sort Direction in a DataGridView

I know that Windows Forms are considered old fashioned, but I've got clients with applications that still use them. As I noted in my previous tip, I recently had to support letting the user sort  by any column in a grid. If I was going to do that, I felt I should let the user know what column and direction they'd just sorted the grid in. The DataGridView lets you do that through the column's SortGlyphDirection property: just set the property to one of SortOrder.Ascending (little arrow in the column header pointing up), SortOrder.Descending (little arrow pointing down), or SortOrder.None (no arrow in the header).

When the user clicks on a column the first time, I sort the column in ascending order; with a second click on the column, I reverse the order. If the user changes columns, I erase the glyph in the previous column. To keep track of the necessary information, I declare two variables outside of any method: The Headers collection keeps track of what direction each column is sorted in, and the OldColumn variable keeps track of the last column sorted:

Private Headers As New Dictionary(Of String, SortOrder)
Private OldColumn As DataGridViewColumn
I put the actual sort code in the DataGridView's ColumnHeaderMouseClick event, whose parameter includes the column position the user's clicked on (the ColumnIndex property). I use that parameter to get a reference to the column the user's selected:

Private Sub CustomersView_ColumnHeaderMouseClick(…    
   Dim col As DataGridViewColumn
   col = Me.CustomersView.Columns(e.ColumnIndex)
In the event handler, I check to see if there's a setting for the current column in the Headers collection. If there isn't, I just sort in ascending order; if there is, I use that value to decide what order to sort the column in:

If Headers.ContainsKey(e.ColumnIndex) = False OrElse
   Headers(e.ColumnIndex) = SortOrder.Descending Then
      Headers(e.ColumnIndex) = SortOrder.Ascending
      Customers = Customers.OrderBy(
            Function(c) prop.GetValue(c, Nothing)).ToList
Else
     Headers(e.ColumnIndex) = SortOrderDescending
     filteredInvoices = filteredInvoices.OrderByDescending(
             Function(c) prop.GetValue(c, Nothing)).ToList
End If

After I finish sorting, I refresh my grid's DataSource with the new collection, clear the sorting glyph in the previous column, set the glyph in the column I'd just sorted, and keep track of which column I've just sorted for next time:

CustomersView.DataSource = Customers
If OldColumn IsNot Nothing Then
   OldColumn.HeaderCell.SortGlyphDirection = Windows.Forms.SortOrder.None
End If
col.HeaderCell.SortGlyphDirection = Headers(e.ColumnIndex)
OldColumn = col

Now, by glancing at the grid's column headers, the user knows which column was sorted last, and in what order.

Posted by Peter Vogel on 10/17/2013


comments powered by Disqus

Featured

Subscribe on YouTube