DataGridView 使用数据源自定义排序
在我的 C# .NET 应用程序中,我有一个 DataGridView。网格的DataSource是BindingSource,BindSource绑定到经常从SQL请求的DataTable的过滤后的DataView。
我已经可以对网格中的列进行排序,但排序始终是按单元格中显示的任何数据值的字符串版本按字母顺序完成的。我有一些显示名称的字段,但需要按特定值而不是按字母顺序排序。我还有一个字段可以是数字或“未知”一词。我需要能够自定义排序背后的逻辑。
我知道我无法使用网格的 SortCompare 事件,因为我正在使用绑定的数据源。我尝试创建显示从 IComparable 派生的自定义类的列,但对该列进行排序仍然始终按字母顺序排序,而不是使用我的 Compare() 方法。
我找到了一种可能的解决方案,其中涉及保留一个隐藏的 DataGridViewColumn 来存储用于排序的数字,并使用网格的 ColumnHeaderMouseClick 事件在用户单击“显示”列时强制它在该隐藏的“排序”列上进行排序。但是,列标题的“排序字形”(显示在排序列上的小向上/向下箭头图标)不会弹出,因为实际的排序列是隐藏的。我已尝试手动设置列的 HeaderCell.SortedGlyphDirection 属性,但如果 BindingSource 的排序不适合该列,则该图标将始终隐藏。
我非常确定,如果我使用为每个数据行创建的自定义包装器对象的可排序列表而不是 DataTable 的 DataView,我就可以实现此功能,但如果可能的话,我不想诉诸于此。但如果这是我唯一的选择,我就会这么做。
In my C# .NET application, I have a DataGridView. The grid's DataSource is a BindingSource, and the BindSource is bound to a filtered DataView of a DataTable that is requeried from SQL frequently.
I can already sort columns in the grid, but the sort is always done alphabetically on the string version of whatever data value is showing in the cells. I have some fields that display a name, but need to be ordered by a specific value instead of alphabetically. I also have a field that can either be a number or the word "Unknown". I need to be able to customize the logic behind the sort.
I know I can't use the grid's SortCompare event because I am using a bound DataSource. I have tried creating columns that display a custom class that derive from IComparable, but sorting on that column still always sorts alphabetically instead of using my Compare() method.
I found one possible solution that involves keeping a hidden DataGridViewColumn that stores a number for sorting on, and using the grid's ColumnHeaderMouseClick event to force it to sort on that hidden "sort" column when the user clicks on the "display" column. However, the column header's "sort glyph" (the little up/down arrow icon that shows up on the sorted column) won't shot up because the actual sorted column is hidden. I have tried manually setting the column's HeaderCell.SortedGlyphDirection property, but the icon will always be hidden if the BindingSource's sort is not for that column.
I'm pretty sure I could get this working if, instead of a DataView of a DataTable, I used a sortable List of a custom wrapper objects I create for each data row, but I don't want to resort to that if possible. But if that's my only option, that's what I'll do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论