1
votes

I populate my datagridview using

dataGridView1.DataSource = ListOfClasses

This fills everything out properly. Now I like to make the columns sortable. They don't seem to sort even though the two columns I tried were longs and a string. I tried running this after the datasource (before gives me an exception as the columns dont exist)

foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                dataGridView1.Columns[column.Name].SortMode = DataGridViewColumnSortMode.Automatic;
            }

I can sort them initially using order by in sql however i still like the flexibility choosing with columns. How do i enable that

3
Your datasource needs to support sorting. You could either bind to a datatable (which support sorting out of the box) or implement your own bindinglist with sorting support. I've given a minimal example in this answer: stackoverflow.com/questions/5700782/… - David Hall

3 Answers

0
votes

Your data source should be a IBindingList.

If you use VS 2010 and above, and EF, you have the method ".ToBindingList();" which does it for you.

ex:

dbContext.YourEntitycollection.Load();
yourBindingSource.DataSource = dbContext.YourEntitycollection.Local.ToBindingList();

Like this, the sorting in your DataGrid is automatically enabled.

For more info see : http://msdn.microsoft.com/en-us/data/jj682076.aspx

0
votes
    void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {

        if (dataGridView1.SortOrder.ToString() == "Ascending") // Check if sorting is Ascending
        {
            dataGridView1.Sort(dataGridView1.Columns[dataGridView1.SortedColumn.Name], ListSortDirection.Descending);
        }
        else
        {
            dataGridView1.Sort(dataGridView1.Columns[dataGridView1.SortedColumn.Name], ListSortDirection.Ascending);
        }
    }