【问题标题】:DataGridView Sort throws exception: Control must be bound to IBindingListDataGridView 排序抛出异常:控件必须绑定到 IBindingList
【发布时间】:2012-12-31 03:39:13
【问题描述】:

我正在使用实体框架 (EF),并且有一个可以从上下文中获取的 BindingList(使用 DbExtensions.ToBindingList 方法),并且我有一个带有 DataGridView 的表单。

目标是在DataGridView 上显示EF 表的内容,所以我在表单的构造函数中有以下代码DataGridViewDataSource 设置为BindingSourceBindingSourceDataSource 到 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。
  • 那行得通。谢谢!虽然我使用BindingSourceBindingNavigator 进行通信,但我会玩弄它,看看我是否可以绕过。
  • 编辑指出在表单的构造函数中调用了 Sort,但可以从其他任何地方调用。

标签: c# winforms entity-framework sorting datagridview


【解决方案1】:

看起来categoryBindSrc.DataSource = _context.Categories.Local.ToBindingList(); 行在调用 Sort 时一定正在调用另一个尚未完成的线程,因此SortDataBoundDataGridView_PerformCheck 检查的几个属性尚未更新。

因此,解决方案是在该线程完成后调用该方法。一个很好的放置它的地方是通过覆盖表单的 OnLoad 方法并在那里调用 Sort 来实现它在用户看到它们之前对数据成员进行排序的效果。

【讨论】:

    猜你喜欢
    • 2013-01-22
    • 2011-06-11
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 1970-01-01
    • 2012-07-23
    • 2020-01-27
    相关资源
    最近更新 更多