2010-12-16 106 views
18

我有一个链接到BindingSourceDataGridView如何将DataGridView绑定到链接到EF4实体的绑定源时排序

BindingSource链接到实体的IQueryable列表:

public void BindTo(IQueryable elements) 
    { 
     BindingSource source = new BindingSource(); 
     source.DataSource = elements; 

     bindingNavigator1.BindingSource = source; 
     dataGridView1.DataSource = source; 

    } 

我希望我的用户能够点击网格标题对数据 - 努力得到这个工作。可能吗?如果是这样,我该怎么做?

+0

注意:DataGridView似乎是WindowsForms,而不是WPF。只为那些也希望为他们的WPF DataGrid排序问题找到解决方案的人。 – OneWorld 2013-01-15 08:24:05

回答

11

我最近在解决这个问题,似乎IQueryable接口不能为DataViewGrid提供足够的信息来知道如何自动对数据进行排序;所以你必须无论是从实体源使用的东西它可以使用或做什么,我没有和手动处理排序功能重新包装您的收藏:

 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; 
    } 

我希望帮助。

+0

有没有办法做到这一点,同时允许更新?如果您使用ToList(),您将只能写入临时列表,并且如果您不使用ToList,则DataGridView似乎禁用添加记录,如果它绑定到IOrderedEnumerable ... – 2011-09-17 18:21:50

+1

我意识到我需要调用ObjectQuery.OrderBy,而不是IEnumerable.OrderBy来维护可更新的绑定。 – 2011-09-17 18:48:11

0

VB.NET

如果您使用的LINQ语法的BindingSource可以当装载有一个DataGridView从实体framwork相关的bindningsource对象“NCFILE数据这样

在这种情况下进行排序“与具有对外列清单‘NCFilePartSet’

bsFileSections.DataSource = From ncfps In NCFile.NCFilePartSet Order By ncfps.Sort Select ncfps 

或类似这样的

bsFileSections.DataSource = NCFile.NCFilePartSet.OrderBy(Function(ncfps) ncfps.Sort) 

其中“排序”是NCFilePartSet

更新的实体继续工作,反映到数据库中

+2

OP要“让我的用户......点击网格标题来排序数据。”如果您对排序列进行硬编码,则您的答案有效,但是当用户想要更改排序列并且不丢失任何已编辑/添加的数据时,如何处理数据绑定?我认为这是真正的挑战。 – Pat 2013-07-11 14:42:08

0

是的,这可以轻松拥有一个可排序的DGV时势必EF数据。使用BLW library中的BindingListView(同样,请查看How do I implement automatic sorting of DataGridView?)。

public void BindTo(IQueryable elements) 
{ 
    BindingSource source = new BindingSource(); 
    source.DataSource = new BindingListView(elements.ToList()); 

    bindingNavigator1.BindingSource = source; 
    dataGridView1.DataSource = source; 

} 

在我的测试,即使.ToList()被构造(如上)中调用,变化传播到数据库,这让我吃惊。

相关问题