如何在绑定到链接到 EF4 实体的绑定源时对 DataGridView 进行排序 [英] How to sort DataGridView when bound to a binding source that is linked to an EF4 Entity
问题描述
我有一个 DataGridView
链接到一个 BindingSource
.
I have a DataGridView
that is linked to a BindingSource
.
我的 BindingSource
链接到一个 IQueryable
实体列表:
My BindingSource
is linked to an IQueryable
list of entities:
public void BindTo(IQueryable elements)
{
BindingSource source = new BindingSource();
source.DataSource = elements;
bindingNavigator1.BindingSource = source;
dataGridView1.DataSource = source;
}
我希望我的用户能够点击网格标题来对数据进行排序 - 努力让它发挥作用.是否可以?如果是这样,我该怎么做?
I am wanting my users to be able to click on the grid headers to sort the data - struggling to get this to work. Is it possible? If so, how do I do it?
推荐答案
我最近也遇到了同样的问题;似乎 IQueryable 接口没有为 DataViewGrid 提供足够的信息来了解如何自动对数据进行排序;所以你必须使用它可以使用的东西从实体源重新打包你的集合,或者做我所做的并手动处理排序功能:
I recently struggled with this same issue; it seems that the IQueryable interface doesn't provide enough information for the DataViewGrid to know how to sort the data automatically; so you have to either repackage your collection from the Entity source using something it can use or do what I did and handle the sorting functionality manually:
private void myDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn column = myDataGridView.Columns[e.ColumnIndex];
_isSortAscending = (_sortColumn == null || _isSortAscending == false);
string direction = _isSortAscending ? "ASC" : "DESC";
myBindingSource.DataSource = _context.MyEntities.OrderBy(
string.Format("it.{0} {1}", column.DataPropertyName, direction)).ToList();
if (_sortColumn != null) _sortColumn.HeaderCell.SortGlyphDirection = SortOrder.None;
column.HeaderCell.SortGlyphDirection = _isSortAscending ? SortOrder.Ascending : SortOrder.Descending;
_sortColumn = column;
}
希望能帮到你.
这篇关于如何在绑定到链接到 EF4 实体的绑定源时对 DataGridView 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!