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

delete picture delete · Apr 5, 2011 · Viewed 155.5k times · Source

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, Nombre = s.Name, Apellidos = s.LastNameFather + " " + s.LastNameMother, Nacido = s.DateOfBirth })
                                   .OrderBy(s => s.Apellidos)
                                   .ToList();

Now, I use the s.Apellidos as the default sort, but I'd also like to allow users to sort when clicking on the column header.

This sort will not modify the data in any way, it's just a client side bonus to allow for easier searching for information when scanning the screen with their eyes.

Thanks for the suggestions.

Answer

Marshal picture Marshal · Apr 5, 2011

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.