How to enable DataGridView sorting when user clicks on the column header?

前端 未结 15 1005
误落风尘
误落风尘 2020-12-02 15:28

I have a datagridview on my form and I populate it with this:

dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombr         


        
15条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-02 15:35

    One more way to do this is using "System.Linq.Dynamic" library. You can get this library from Nuget. No need of any custom implementations or sortable List :)

    using System.Linq.Dynamic;
    private bool sortAscending = false;
    
    private void dataGridView_ColumnHeaderMouseClick ( object sender, DataGridViewCellMouseEventArgs e )
    {
        if ( sortAscending )
            dataGridView.DataSource = list.OrderBy ( dataGridView.Columns [ e.ColumnIndex ].DataPropertyName ).ToList ( );
        else
            dataGridView.DataSource = list.OrderBy ( dataGridView.Columns [ e.ColumnIndex ].DataPropertyName ).Reverse ( ).ToList ( );
        sortAscending = !sortAscending;
    }
    

提交回复
热议问题