2015-09-16 66 views
3

排序的DataGridView我有一个绑定到被绑定到一个DataSet一个BindingSourceDataGridView。对于大多数列,默认的排序顺序没问题,但对于其中一列,显示的数据不适合排序,并且我在DataSet中有一个隐藏的计算列SortCol,以便为该列做出更好的排序。通过隐藏列

问题是,SortCompare,其中我有代码重定向排序SortCol不会被调用。我一直在谷歌搜索几个小时,似乎每个人都说SortCompareDataSource属性设置为DataGridView - 它期望约束DataSource执行排序时不使用SortCompare - 然后主题被删除,没有任何关于如何实际执行排序的建议。

我查看了BindingSourceDataSet,我没有看到任何公开的接口用于自定义排序。我一切都会设法推出我自己的BindingSource来做到这一点,但我希望有一种方法可以让你更轻松地做出更直接的事情。

编辑:由于似乎有一些混淆,我想澄清,我不问如何执行DataSet或甚至在DataGridView上的初始设置。这是微不足道的。我具体询问如何将点击一列标题链接到另一列的排序(或者更一般地通过其他标准)。

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

UPDATE:没有骰子 - 使用一个Sort超载穿隐藏列SortGlyph,对方给出了一个错误:DataGridView control is data-bound. The control cannot use the comparer to perform the sort operation.

UPDATE:除非你设置SortGlyph排序由另一列。我想这就是我必须解决的问题。尽管我想我会保持开放以防其他人提出更好的答案供将来参考。

回答

2

我终于用于此的解决方案是设置SortModeProgrammatic和处理“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的等价物,但至少它似乎正在工作。