【问题标题】:Sorting DataGridView by Hidden Column按隐藏列对 DataGridView 进行排序
【发布时间】:2015-09-17 08:00:34
【问题描述】:

我有一个绑定到BindingSourceDataGridView 绑定到DataSet。对于大多数列,默认排序顺序很好,但对于其中一列,显示的数据不利于排序,我有一个隐藏的计算列,DataSet 中的SortCol 以进行更好的排序为该列。

问题是,SortCompare,我有代码将排序重定向到SortCol 没有被调用。我已经用谷歌搜索了几个小时,似乎每个人都说DataSource 属性设置在DataGridView 上时不使用SortCompare - 它期望绑定DataSource 执行排序- 然后主题就被删除了,没有任何关于如何实际执行排序的建议。

我查看了BindingSourceDataSet,但没有看到任何用于自定义排序的公开接口。我已经准备好推导出我自己的 BindingSource 来做这件事,但我希望有一种方法可以让我更轻松地去做更简单的事情。

编辑:由于似乎有些混乱,我想澄清一下,我不是在问如何在DataSet 甚至DataGridView 上执行初始设置。那是微不足道的。我特别询问如何将单击一个列标题链接到基于另一列(或更一般地按其他标准)的排序。

我现在正在研究是否可以将Programmatically 设置为SortMode,因为似乎不存在简单的方法。

更新:没有骰子 - 使用一个 Sort 重载将 SortGlyph 放在隐藏列上,另一个给出错误:DataGridView control is data-bound. The control cannot use the comparer to perform the sort operation.

更新:除非您设置 SortGlyph after 按另一列排序。我想这就是我必须采用的解决方案;虽然我认为我会保持开放状态,以防其他人提出更好的答案以供将来参考。

【问题讨论】:

    标签: vb.net sorting datagridview


    【解决方案1】:

    我最终使用的解决方案是将SortMode设置为Programmatic并处理'ColumnHeaderMouseClick'事件如下:

        Private Sub DG_ColumnHeaderMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DG.ColumnHeaderMouseClick
            If DG.Columns(e.ColumnIndex) Is NonSortColumn Then
                Select Case NonSortColumn.HeaderCell.SortGlyphDirection
                    Case SortOrder.Ascending
                        DG.Sort(SortColumn, System.ComponentModel.ListSortDirection.Descending)
                        NonSortColumn.HeaderCell.SortGlyphDirection = SortOrder.Descending
                    Case Else
                        DG.Sort(SortColumn, System.ComponentModel.ListSortDirection.Ascending)
                        NonSortColumn.HeaderCell.SortGlyphDirection = SortOrder.Ascending
                End Select
            End If
        End Sub
    

    与仅处理SortCompare 事件或BindingSourceDataSet 的等效事件相比,它仍然感觉有点麻烦,但至少它似乎可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-12
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 2015-10-30
      • 1970-01-01
      相关资源
      最近更新 更多