DataGridView SortCompare事件不会触发 [英] DataGridView SortCompare event doesn't fire

查看:535
本文介绍了DataGridView SortCompare事件不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用VS2008,C#和.NET 3.5

Using VS2008, C# and .NET 3.5

我正在使用数据绑定的DataGridView控件来显示从Web服务读取的表格数据。在某些情况下,需要对数字列进行排序。我尝试了几种不同的方法来使它起作用,但是该列仍然最终按字母顺序排序(即1、10、2、3而不是1、2、3、10)。

I am using databound DataGridView controls to display tabular data read from a web service. In several cases, there is a numeric column that needs to be sorted. I have tried a couple of different ways to get this to work, but the column still ends up sorting alphabetically (ie, 1, 10, 2, 3 instead of 1, 2, 3, 10).

将列数据类型设置为int不适用于数据绑定控件,因此,执行此操作的唯一真正方法是提供一些自定义排序逻辑。

Setting the column data type to int doesn't work for databound controls, so the only real way to do this is to provide some custom sort logic.

许多人建议挂接到SortCompare事件以提供自定义排序逻辑,但是由于某些原因,该事件代码永远不会运行-我可以在处理程序中放置一个断点,并且它永远不会到达那里。我正在通过GUI添加事件处理程序,因此该处理程序是通过VS而不是手动添加到控件的。

Many people have suggested hooking in to the SortCompare event to provide custom sort logic, but for some reason the event code never runs -- I can put a breakpoint in the handler and it never gets there. I am adding the event handler through the GUI, so the handler is added to the control by VS, not manually.

这里是事件处理程序代码,从此处的某处举起:

Here's the event handler code, lifted from somewhere around here:

    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;
    }

如果这被触发,它将完全按照我的意愿去做。我可能会错过什么?

If this ever fired, it would do exactly what I want it to do. What could I be missing?

感谢指出(希望如此)显而易见的……
戴夫

Thanks for pointing out the (hopefully) obvious... Dave

推荐答案

当DataGridView进行数据绑定时,也可以对数据源进行排序。

When the DataGridView is databound, the datasource can be sorted too.

某些数据源内置了对排序的支持。您的数据源实现IBindingList或IBindingListView排序属性和方法,以各种方式对数据源进行排序。

Some datasources have built in support for sorting. Your datasource implements IBindingList or IBindingListView sorting properties and methods to sort a datasource in various ways.

这篇关于DataGridView SortCompare事件不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆