使用 VS2008、C# 和 .NET 3.5
我正在使用数据绑定(bind) DataGridView 控件来显示从 Web 服务读取的表格数据。在某些情况下,有一个数字列需要排序。我尝试了几种不同的方法来让它工作,但该列最终仍按字母顺序排序(即 1、10、2、3 而不是 1、2、3、10)。
将列数据类型设置为 int 不适用于数据绑定(bind)控件,因此唯一真正可行的方法是提供一些自定义排序逻辑。
许多人建议连接到 SortCompare 事件以提供自定义排序逻辑,但出于某种原因,事件代码永远不会运行——我可以在处理程序中放置一个断点,但它永远不会到达那里。我是通过 GUI 添加事件处理程序,因此处理程序是由 VS 添加到控件中,而不是手动添加。
这是事件处理程序代码,从附近的某个地方提取:
private void uxLicensedSoftwareDataGridView_SortCompare( object sender,
DataGridViewSortCompareEventArgs e )
{
int intValue1, intValue2;
if ( !Int32.TryParse( e.CellValue1.ToString(), out intValue1 ) )
return;
if ( !Int32.TryParse( e.CellValue2.ToString(), out intValue2 ) )
return;
if ( intValue1 == intValue2 )
e.SortResult = 0;
else if ( intValue1 < intValue2 )
e.SortResult = -1;
else
e.SortResult = 1;
e.Handled = true;
}
如果它被触发,它就会完全按照我的意愿去做。我可能缺少什么?
感谢您指出(希望)显而易见的... 戴夫
最佳答案
将每列的排序模式设置为“自动”而不是“程序化”
也来自这个document :
The SortCompare event does not occur when the DataSource property is set or when the VirtualMode property value is true.
关于c# - DataGridView SortCompare 事件不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1362963/