How to sort a DataGridView that is bound to a collection of custom objects?

Abion47 picture Abion47 · Jun 28, 2012 · Viewed 11.8k times · Source

So I have been following this guide for data binding on Windows Forms controls (MAD props to the author, this guide is great), and I have used this to create a custom class and bind a DataGridView to a collection of this class:

class CompleteJobListEntry
{
    private string _jobName;
    private Image _jobStatus;
    private DateTime _jobAddedDate;
    private string _jobAddedScanner;
    private string _jobAddedUser;
    private string _jobLastActivity;
    private DateTime _jobActivityDate;
    private string _jobActivityUser;

    public string JobName { get { return _jobName; } set { this._jobName = value; } }
    public Image JobStatus { get { return _jobStatus; } set { this._jobStatus = value; } }
    public DateTime JobAddedDate { get { return _jobAddedDate; } set { this._jobAddedDate = value; } }
    public string JobAddedScanner { get { return _jobAddedScanner; } set { this._jobAddedScanner = value; } }
    public string JobAddedUser { get { return _jobAddedUser; } set { this._jobAddedUser = value; } }
    public string JobLastActivity { get { return _jobLastActivity; } set { this._jobLastActivity = value; } }
    public DateTime JobActivityDate { get { return _jobActivityDate; } set { this._jobActivityDate = value; } }
    public string JobActivityUser { get { return _jobActivityUser; } set { this._jobActivityUser = value; } }
}

At this point, I import a bunch of data from various SQL databases to populate the table, and it turns out great. The guide even provides an excellent starting point for adding filters, which I intend to follow a bit later. For now, though, I am stuck on the sorting of my newly generated DataGridView. Looking around, I've discovered that the DataGridView has its own Sort method, usable like:

completeJobListGridView.Sort(completeJobListGridView.Columns["JobName"], ListSortDirection.Ascending);

However, when I try to do this, I get an InvalidOperationException that tells me "DataGridView control cannot be sorted if it is bound to an IBindingList that does not support sorting." I've found both the IBindingList and IBindingListView interfaces, but making my class inherit either of these interfaces doesn't solve the problem.

How do I do this? I am completely stuck here...

Answer

Pat picture Pat · Jul 30, 2013

If your data is in a collection, you should be able to use the BindingListView library to easily add sorting capabilities to your DGV. See How do I implement automatic sorting of DataGridView? and my answer to How to Sort WinForms DataGridView bound to EF EntityCollection<T> for more information and code snippets.