c# - 绑定(bind)到链接到 EF4 实体的绑定(bind)源时如何对 DataGridView 进行排序

标签 c# winforms entity-framework sorting datagridview

我有一个链接到 BindingSourceDataGridView

我的 BindingSource 链接到 IQueryable 实体列表:

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

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

    }

我希望我的用户能够点击网格标题来对数据进行排序——努力让它发挥作用。可能吗?如果是这样,我该怎么做?

最佳答案

我最近也在为同样的问题苦苦挣扎;似乎 IQueryable 接口(interface)没有为 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;
  }

希望对您有所帮助。

关于c# - 绑定(bind)到链接到 EF4 实体的绑定(bind)源时如何对 DataGridView 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4463505/

相关文章:

c# - 带有 Ninject 拦截、CaSTLe DynamicProxy 和 WPF 窗口的 AOP : Can't find XAML resource in DynamicProxy of window

c# - ExecuteStoreQuery 和 ExecuteStoreCommand 有什么区别

c# - 保存枚举时值不正确

entity-framework - 如何在Entity Framework 6中执行搜索?

C# 数据绑定(bind) : Create object if null

c# - Alpha channel 无法按预期使用 WriteableBitmap

c# - 在 Contains 方法中的 linq 查询中使用字典

c# - 按顺序使用数组获取文件

javascript - 如何从 webbrowser C# 返回 javascript 函数值

c# - 将标签文本显示为警告消息并在几秒钟后隐藏?