Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridViewColumn initial sort direction

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

like image 784
lnediger Avatar asked Jul 28 '09 12:07

lnediger


3 Answers

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;
like image 196
SwDevMan81 Avatar answered Sep 21 '22 21:09

SwDevMan81


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;
    }
}
like image 33
Christopher Galpin Avatar answered Sep 23 '22 21:09

Christopher Galpin


I suggest below code

MyDGV.Sort(MyDGV.Columns[column_Index], ListSortDirection.Ascending);
like image 5
sam Avatar answered Sep 20 '22 21:09

sam