C# 数据源绑定时DataGridView自动排序不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15439816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
DataGridView automatic sorting doesn't work when datasource bound
提问by mandrive
My problem is: when I bind datasource to DataGridView
我的问题是:当我将数据源绑定到 DataGridView
BindingList<Contract> contracts = new BindingList<Contract>(Contract.GetAll());
dgEndingContracts.DataSource = contracts.Where(c => c.ExpirationDate <= nextMonth && c.IsArchived == false).ToList();
and set every column to SortMode = DataGridViewColumnSortMode.Automatic
when I click on dataGridView header rows doesn't sort.
并将每一列设置为SortMode = DataGridViewColumnSortMode.Automatic
当我单击 dataGridView 标题行时不排序。
But when I manually create each column, create and fill with data each row of dataGridView, and the set column sort mode to automatic, sorting works fine.
但是当我手动创建每一列,创建并填充dataGridView的每一行数据,并将列排序模式设置为自动时,排序工作正常。
What is the difference and how can I enable sorting in first approach?
有什么区别,如何在第一种方法中启用排序?
采纳答案by mandrive
I 've found solution.
我找到了解决办法。
It's seems that DataGridView can't sort either List <T>
or BindingList<T>
似乎 DataGridView 无法排序List <T>
或BindingList<T>
So I've added class SortedBindingList<T>
based on code from:
and now my DataGridView
can sort columns.
所以我class SortedBindingList<T>
根据来自: 的代码进行了添加,现在我DataGridView
可以对列进行排序。
Thanks for help guys.
谢谢你们的帮助。
回答by Slava
.ToList() doesn't return something that implements IBindingList. Use something, like thtat:
.ToList() 不返回实现 IBindingList 的内容。使用一些东西,例如:
dgEndingContracts.DataSource = new BindingList<Contract>(contracts.Where(c => c.ExpirationDate <= nextMonth && c.IsArchived == false).ToList());