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

前端 未结 15 965
误落风尘
误落风尘 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条回答
  •  Happy的楠姐
    2020-12-02 15:54

    You don't need to create a binding datasource. If you want to apply sorting for all of your columns, here is a more generic solution of mine;

    private int _previousIndex;
    private bool _sortDirection;
    
    private void gridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.ColumnIndex == _previousIndex)
            _sortDirection ^= true; // toggle direction
    
        gridView.DataSource = SortData(
            (List)gridReview.DataSource, gridReview.Columns[e.ColumnIndex].Name, _sortDirection);
    
        _previousIndex = e.ColumnIndex;
    }
    
    public List SortData(List list, string column, bool ascending)
    {
        return ascending ? 
            list.OrderBy(_ => _.GetType().GetProperty(column).GetValue(_)).ToList() :
            list.OrderByDescending(_ => _.GetType().GetProperty(column).GetValue(_)).ToList();
    }
    

    Make sure you subscribe your data grid to the event ColumnHeaderMouseClick. When the user clicks on the column it will sort by descending. If the same column header is clicked again, sorting will be applied by ascending.

提交回复
热议问题