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

前端 未结 15 934
误落风尘
误落风尘 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;
    }
    
    0 讨论(0)
  • 2020-12-02 15:37


    there is quite simply solution when using Entity Framework (version 6 in this case). I'm not sure but it seems to ObservableCollectionExtensions.ToBindingList<T> method returns implementation of sortable binding list. I haven't found source code to confirm this supposition but object returning from this method works with DataGridView very well especially when sorting columns by clicking on its headers.

    The code is very simply and relies only on .net and entity framework classes:

    using System.Data.Entity;
    
    IEnumerable<Item> items = MethodCreatingItems();
    
    var observableItems = new System.Collections.ObjectModel.ObservableCollection<Item>(items);
    System.ComponentModel.BindingList<Item> source = observableItems.ToBindingList();
    
    MyDataGridView.DataSource = source;
    
    0 讨论(0)
  • 2020-12-02 15:39

    Set all the column's (which can be sortable by users) SortMode property to Automatic

    dataGridView1.DataSource = students.Select(s => new { ID = s.StudentId, RUDE = s.RUDE, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth })
                                       .OrderBy(s => s.Apellidos)
                                       .ToList();
    
        foreach(DataGridViewColumn column in dataGridView1.Columns)
        {
    
            column.SortMode = DataGridViewColumnSortMode.Automatic;
        }
    

    Edit: As your datagridview is bound with a linq query, it will not be sorted. So please go through this link which explains how to create a sortable binding list and to then feed it as datasource to datagridview.

    0 讨论(0)
  • 2020-12-02 15:43

    I suggest using a DataTable.DefaultView as a DataSource. Then the line below.

    foreach (DataGridViewColumn column in gridview.Columns)
        {
           column.SortMode = DataGridViewColumnSortMode.Automatic;
        }
    

    After that the gridview itself will manage sorting(Ascending or Descending is supported.)

    0 讨论(0)
  • 2020-12-02 15:43

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

    BindingList x1;
    x1 = new BindingList<sourceObject>();
    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<sourceObject>(); // 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.

    0 讨论(0)
  • 2020-12-02 15:46

    Just in case somebody still looks for it, I did it on VS 2008 C#.

    On the Event ColumnHeaderMouseClick, add a databinding for the gridview, and send the order by field like a parameter. You can get the clicked field as follows:

    dgView.Columns[e.ColumnIndex].Name
    

    In my case the header's names are similar to view field names.

    0 讨论(0)
提交回复
热议问题