Get and Set sortation (Column and Ascending/Descending) of a DataGridView

reijin picture reijin · May 29, 2012 · Viewed 8k times · Source

I'm having a small problem. I need to save the sortation (by which Column and Ascending or Descending) and load it on the next start of the program. Getting the currently selected Column is no problem i do this via

    private int GetSortColumn()
    {
        DataGridViewColumn sortColumn = this.dataGridView.SortedColumn;
        if (sortColumn != null)
        {
            Properties.Settings.Default.sortingColumnSortMode = dataGridView.SortOrder;
            return sortColumn.Index;
        }
        else
            //error
            return -1;
    }

And save the data in my settings. Setting this property is also no problem:

    private void SetSortColumn(int indexOfColumn)
    {
        if (indexOfColumn != null && indexOfColumn != -1)
        {
            this.dataGridView.Sort(this.dataGridView.Columns[indexOfColumn], ListSortDirection.Descending);
        }
    }

But I need to save and set the ascending or descending property also. How do I do this? Is there a way to get a ListSortDirection with the dataGridView.SortedColumn? Or is there a better solution to set if the dataGridView is sorted in ascending or descending order?

Thanks and greetings! reijin

Answer

reijin picture reijin · May 29, 2012

ok, I was able to fix my problem by simply adding a switch in my SetSortColumn:

    private void SetSortColumn(int indexOfColumn)
    {
        if (indexOfColumn != null && indexOfColumn != -1)
        {
            ListSortDirection listSort;
            switch (Properties.Settings.Default.sortingColumnSortMode)
            {
                case SortOrder.Ascending:
                    listSort = ListSortDirection.Ascending;
                    break;

                case SortOrder.Descending:
                    listSort = ListSortDirection.Descending;
                    break;

                default:
                    listSort = ListSortDirection.Descending;
                    break;

            }

            this.dataGridView.Sort(this.dataGridView.Columns[indexOfColumn], listSort);
        }
    }

Maybe it will help others ;)