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

拟墨画扇 提交于 2020-01-24 10:27:07

问题


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...


回答1:


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.



来源:https://stackoverflow.com/questions/11236109/how-to-sort-a-datagridview-that-is-bound-to-a-collection-of-custom-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!