DataGridView 单元格自定义
我想为 datagridview 创建一个单元格,它接受 Int64 值以便排序。
此外,该单元格将显示一个额外的值,该值是当前值与我在 datagridview 之外的参考值的差值。
我可以将其作为字符串,但排序将无法正确处理,因为它看起来像 1, 10, 11, 2.... 等等。
所以我想,如果我可以创建一个自定义单元格并定义很长的单元格值并显示一个字符串,那就太好了...但我不确定这是否可以实现...
有人知道这如何实现吗可以通过简单的方式完成吗?请注意,我正在手动加载 datagridview,但我正在定义列类型以允许排序。
I would like to create a cell for the datagridview that would accept a Int64 value in order to sort.
Additionally that cell will display an extra value that is the difference of the current value with a reference value I have outside the datagridview.
I could do it as string but the sorting will not be correctly handled because it would look like 1, 10, 11, 2.... and so on.
So I thought that if I could create a custom cell and define the cell value the long and display a string it would be great... but I'm not sure if this can be accomplished....
Does someone know how can this be accomplished in a simple way? Note that I am loading the datagridview manually but I am defining the column types to allow sorting.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种相当简单的方法是使用 DataGridView 的
SortCompare
事件。使用该事件检查正在排序的列是否显示您的自定义数据,如果是,则提取该数据的数字部分并对其进行排序。下面我有一个例子:
假设:
- 包含自定义数据的列位于列索引 1
- 您的自定义数据由一个数字组成,后跟至少一个空格
我的代码还假设单元格值的转换永远不会引发错误。您的数据可能包含会导致此转换失败的值。在这种情况下,您可以做的是在转换之前验证您的数据(它不为空等),如果验证失败,请将用于排序目的的单元格的数值设置为 -1 或其他值,以便它始终低于中的有效值其他细胞。 (我希望这是有道理的)。
这篇 MSDN 文章 很好地描述了应用这些类型的排序。您可能想看一下。其中一个示例显示了在平局情况下您可以执行的操作(该示例显示了在另一列上进行排序作为排序平局)。
One fairly easy way to do this is to use the DataGridView's
SortCompare
event. Use the event to check that the column being sorted displays your custom data and if so extract the number portion of that data and do your sort on it.Below I have an example:
Assumptions:
- that the column with your custom data is at column index 1
- that your custom data consists of a number followed by at least one space
My code also assumes that the conversion of the cells' value will never throw an error. It's possible that your data includes values that would cause this conversion to fail. What you could do in that case is validate your data before the conversion (that it's not null, etc.) and if of the validation fails set the cell's numeric value for sorting purposes to -1 or something so it's always lower than valid values in other cells. (I hope that made sense).
Applying these types of sorts is pretty well described in this MSDN article. You'll probably want to take a look. One of the examples show what you can do in the case of ties (the example shows sorting on another column as the sort tiebreaker).