Reputation: 3758
I'm using Entity Framework (EF), and have a BindingList
I can get from the context (using the DbExtensions.ToBindingList method), and I have a form with a DataGridView
.
The objective is to display the contents of the EF table on the DataGridView
, so I have the following code in the form's constructor to set the DataGridView
's DataSource
to a BindingSource
and that BindingSource
's DataSource
to the BindingList
from EF:
categoryBindSrc.DataSource = _context.Categories.Local.ToBindingList();
categoryDataGrid.Sort(categoryDataGrid.Columns["categorySortIdColumn"], ListSortDirection.Ascending);
Before that, in the Form's generated code, these lines exist:
categoryDataGrid.DataSource = categoryBindSrc;
categorySortIdColumn.DataPropertyName = "SortId";
This code is in the form's constructor, but when I run it, I get the following exception (I truncated the stack trace):
System.InvalidOperationException was unhandled
HResult=-2146233079
Message=DataGridView control must be bound to an IBindingList object to be sorted.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.DataGridView.SortDataBoundDataGridView_PerformCheck(DataGridViewColumn dataGridViewColumn)
at System.Windows.Forms.DataGridView.SortInternal(IComparer comparer, DataGridViewColumn dataGridViewColumn, ListSortDirection direction)
at System.Windows.Forms.DataGridView.Sort(DataGridViewColumn dataGridViewColumn, ListSortDirection direction)
To my understanding, BindingList
does implement IBindingList
so that shouldn't be the problem. The Sort method says the DataGridView
must be data-bound (it is) and that the sort-by-column's DataPropertyName
property is set (it is) which causes the column's IsDataBound
property to return true (when debugging it shows false in the watch window)
It seems that the problem is that IsDataBound
isn't getting updated, but I don't know what SortDataBoundDataGridView_PerformCheck
(the method that threw the exception) checks for exactly, or why IsDataBound
wouldn't be set.
I tried to provide all the code you need to understand the question, but let me know if you need more. I also checked several related questions on S/O--none of the answers helped.
EDIT: It appears I can call Sort just fine from any other method except the constructor. This might be a threading issue.
Upvotes: 2
Views: 5462
Reputation: 3758
Looks like the line categoryBindSrc.DataSource = _context.Categories.Local.ToBindingList();
must be calling another thread that hasn't finished when Sort is called, so a couple of properties that are checked by SortDataBoundDataGridView_PerformCheck
haven't been updated yet.
Therefore, the solution is to call the method after that thread has finished. A nice place to put it so it still achieves its affect of sorting the data members before the users sees them is by overriding the form's OnLoad method and calling Sort there.
Upvotes: 1