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

前端 未结 15 944
误落风尘
误落风尘 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:43

    I have a BindingList<> object bind as a data source to dataGridView.

    BindingList x1;
    x1 = new BindingList();
    BindingSource bsx1 = new BindingSource();
    bsx1.DataSource = x1;
    dataGridView1.DataSource = bsx1;
    

    When I clicked the column header, no sorting takes place. I used the SortableBindingList answer provided by Tom Bushell. Having included two source files into my project

    1. SortableBindingList.cs
    2. PropertyComparer.cs

    Then this change is made to my code:

    Be.Timvw.Framework.ComponentModel.SortableBindingList x1;                       // 1
    x1 = new Be.Timvw.Framework.ComponentModel.SortableBindingList(); // 2
    BindingSource bsx1 = new BindingSource();
    bsx1.DataSource = x1;
    dataGridView1.DataSource = bsx1;
    

    After these changes I performed a build on my program. I am now able to sort by clicking the column headers. Only two lines need changing, they are highlighted in the code snippet above by trailing comments.

提交回复
热议问题