Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
A DGV column, which wasn't sorted before, is sorted ascending by the first column header click.
Is it possible to start with decending sort first ?
Thanks

What I have tried:

DGV1.Columns("XYZ").SortMode = DataGridViewColumnSortMode.Automatic
Posted
Updated 7-Oct-21 2:39am

1 solution

There's an example of how to control the sorting in the documentation:
DataGridView.ColumnHeaderMouseClick Event (System.Windows.Forms) | Microsoft Docs[^]

You just need to determine the default sort order based on the sort column in the ColumnHeaderMouseClick event handler.
C#
DataGridViewColumn newColumn = dataGridView1.Columns[e.ColumnIndex];
DataGridViewColumn oldColumn = dataGridView1.SortedColumn;
ListSortDirection direction;

if (oldColumn == newColumn)
{
    // Sorting by the same column: toggle between ASC and DESC:
    direction = dataGridView1.SortOrder == SortOrder.Ascending 
        ? ListSortDirection.Descending 
        : ListSortDirection.Ascending;
}
else
{
    // Sorting by a new column.
    
    // Choose the default direction based on the column name:
    switch (column.Name)
    {
        case "XYZ":
            direction = ListSortDirection.Descending;
            break;
        default:
            direction = ListSortDirection.Ascending;
            break;
    }

    // Remove the sorting glyph from the old column, if any:
    if (oldColumn != null)
    {
        oldColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
    }
}

dataGridView1.Sort(newColumn, direction);

newColumn.HeaderCell.SortGlyphDirection = direction == ListSortDirection.Ascending 
    ? SortOrder.Ascending 
    : SortOrder.Descending;
 
Share this answer
 
Comments
Rainer Heer 7-Oct-21 9:24am    
Very good idea !

If NewColumn <> OldColumn then
DefaultView.Sort = NewColumn & " DESC"
else
No additional changes necessary
endif

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900