views:

304

answers:

3

I'm working in VS2008 on a C# WinForms app. By default when clicking on a column header in a DataGridView it sorts that column Ascending, you can then click on the column header again to sort it Descending.

I am trying to reverse this, so the initial click sorts Descending then the second click sorts Ascending and I haven't been able to figure out how to do this. Does anyone know?

Thanks

A: 

Take a look at DataGridView.SortCompare. See slightly modified version of the msdn example below:

private void dataGridView1_SortCompare(object sender,
        DataGridViewSortCompareEventArgs e)
    {
        // Try to sort based on the cells in the current column.
        e.SortResult = System.String.Compare(
            e.CellValue2.ToString(), e.CellValue1.ToString()); // descending sort

        e.Handled = true;
    }
Vivek
+1  A: 

You can set the HeaderCell SortGlyphDirection to Ascending, and then the next click will give you the descending order. The default is none.

dataGridView1.Sort(Column1, ListSortDirection.Ascending);
this.Column1.HeaderCell.SortGlyphDirection = System.Windows.Forms.SortOrder.Ascending;
SwDevMan81
I believe this will only change the 'glyph' not the sort order - i.e the image shown on the column header: ▲ or ▼
Vivek
Ah, you are right, youd have to sort the column too, I updated above
SwDevMan81
And I guess once you sort, you dont need to set the SortGlyphDirection
SwDevMan81
This will work for a single particular column, but I'm trying to get all columns to sort descending the first time they are clicked on.
lnediger
You could just do a foreach loop on dataGridView.Columns and sort them all. Not the most efficient way, but it should work.
SwDevMan81
+1  A: 
foreach (DataGridViewColumn column in DataGridView1.Columns)
{
    column.SortMode = DataGridViewColumnSortMode.Programmatic;
}

and

private void DataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    var column = DataGridView1.Columns[e.ColumnIndex];
    if (column.SortMode != DataGridViewColumnSortMode.Programmatic)
        return;

    var sortGlyph = column.HeaderCell.SortGlyphDirection;
    switch (sortGlyph)
    {
        case SortOrder.None:
        case SortOrder.Ascending:
            DataGridView1.Sort(column, ListSortDirection.Descending);
            column.HeaderCell.SortGlyphDirection = SortOrder.Descending;
            break;
        case SortOrder.Descending:
            DataGridView1.Sort(column, ListSortDirection.Ascending);
            column.HeaderCell.SortGlyphDirection = SortOrder.Ascending;
            break;
    }
}
Christopher Galpin