C# – How to implement automatic sorting of DataGridView

cdatagridviewsorting

I am programmatically adding columns to a DataGridView and then binding to a list. By default, the SortMode of the columns are Automatic. But when I run my app, clicking on the headers does nothing. The up/down arrows aren't showing up. From reading MSDN, not much is said about automatic sorting. They go into more detail about programmatic sorting. So, I'm assuming the automatic way should be easy. MSDN goes on to say "Unless column headers are used for selection, clicking the column header automatically sorts the DataGridView by this column and displays a glyph indicating the sort order." What exactly does that mean? Could I be setting a grid property that conflicts with the sorting? What am I missing?

AutoGenerateColumns = false;
AllowUserToAddRows = false;
AllowUserToDeleteRows = false;
AllowUserToResizeRows = false;
AllowUserToResizeColumns = false;
ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
ReadOnly = true;
MultiSelect = false;
RowHeadersVisible = false;
SelectionMode = DataGridViewSelectionMode.FullRowSelect;
CellBorderStyle = DataGridViewCellBorderStyle.None;


    DataGridViewTextBoxColumn idColumn = new DataGridViewTextBoxColumn();
    idColumn.HeaderText = "ID";
    idColumn.DataPropertyName = "IDNumber";

    DataGridViewTextBoxColumn nameColumn = new DataGridViewTextBoxColumn();
    nameColumn.HeaderText = "Name";
    nameColumn.DataPropertyName = "Description";

    DataGridViewTextBoxColumn lastModifiedColumn = new DataGridViewTextBoxColumn();
    lastModifiedColumn.HeaderText = "Last Modified";
    lastModifiedColumn.DataPropertyName = "Date";

    Columns.Add(idColumn);
    Columns.Add(nameColumn);
    Columns.Add(lastModifiedColumn);

    List<IMyObject> bindingList = GetMyList();
    DataSource = bindingList;

Best Answer

We use BindingListView to bind List<T>s to DataGridViews, and it's worked beautifully for us.

Here is a very simple example of creating a view of a list of objects (in C#):

List<Customer> customers = GetCustomers();
BindingListView<Customer> view = new BindingListView<Customer>(customers);
dataGridView1.DataSource = view;

Check out https://stackoverflow.com/a/17952576/116891 for a lot more details about DGV sorting and databinding.

If you don't want to add something that heavy, you can try this implementation of a SortableBindingList<T> (with updates).

Both give you sorting right out of the box, and BindingListView is even faster than DataViews, according to their benchmarks.