一种相当简单的方法是使用 DataGridView 的SortCompare
事件。使用该事件检查正在排序的列是否显示您的自定义数据,如果是,则提取该数据的数字部分并对其进行排序。
下面我有一个例子:
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e) {
if (e.Column.Index == 1) { // This is your custom data's column.
// Extract the numeric values from the cells being compared for the sort.
// BEWARE: code assumes you'll always be able to extract a long from the cell contents.
long cell1NumericValue = Int64.Parse(e.CellValue1.ToString().Split(' ')[0]);
long cell2NumericValue = Int64.Parse(e.CellValue2.ToString().Split(' ')[0]);
// Compare these numeric values to determine how to sort.
e.SortResult = cell1NumericValue.CompareTo(cell2NumericValue);
e.Handled = true;
}
}
假设:
- 包含您的自定义数据的列位于列索引 1
- 您的自定义数据由一个数字组成,后跟至少一个空格
我的代码还假设单元格值的转换永远不会引发错误。您的数据可能包含会导致此转换失败的值。在这种情况下,您可以做的是在转换之前验证您的数据(它不是 null 等),如果验证失败,请将单元格的数值设置为 -1 或其他值,以便它始终低于有效值其他细胞。(我希望这是有道理的)。
这篇 MSDN 文章很好地描述了应用这些类型的类型。你可能想看看。其中一个示例显示了在出现平局的情况下您可以做什么(该示例显示在另一列上进行排序作为排序决胜局)。