【发布时间】:2012-12-31 03:39:13
【问题描述】:
我正在使用实体框架 (EF),并且有一个可以从上下文中获取的 BindingList(使用 DbExtensions.ToBindingList 方法),并且我有一个带有 DataGridView 的表单。
目标是在DataGridView 上显示EF 表的内容,所以我在表单的构造函数中有以下代码 将DataGridView 的DataSource 设置为BindingSource 和 BindingSource 的 DataSource 到 EF 的 BindingList:
categoryBindSrc.DataSource = _context.Categories.Local.ToBindingList();
categoryDataGrid.Sort(categoryDataGrid.Columns["categorySortIdColumn"], ListSortDirection.Ascending);
在此之前,在表单生成的代码中,存在以下几行:
categoryDataGrid.DataSource = categoryBindSrc;
categorySortIdColumn.DataPropertyName = "SortId";
这段代码在表单的构造函数中,但是当我运行它时,我得到了以下异常(我截断了堆栈跟踪):
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)
据我了解,BindingList 确实实现了IBindingList,所以这应该不是问题。 Sort 方法说 DataGridView 必须是数据绑定的(它是)并且按列排序的 DataPropertyName 属性已设置(它是)导致列的 IsDataBound 属性返回true(调试时在监视窗口中显示为 false)
问题似乎在于IsDataBound 没有得到更新,但我不知道SortDataBoundDataGridView_PerformCheck(引发异常的方法)究竟检查了什么,或者为什么IsDataBound 不会设置。
我试图提供您理解问题所需的所有代码,但如果您需要更多代码,请告诉我。我还检查了几个关于 S/O 的相关问题——没有一个答案有帮助。
编辑: 看来我可以从构造函数以外的任何其他方法调用 Sort 就好了。这可能是线程问题。
【问题讨论】:
-
尝试将datagridview数据源直接设置为IBindingList。
-
那行得通。谢谢!虽然我使用
BindingSource与BindingNavigator进行通信,但我会玩弄它,看看我是否可以绕过。 -
编辑指出在表单的构造函数中调用了 Sort,但可以从其他任何地方调用。
标签: c# winforms entity-framework sorting datagridview