0

我有一个包含列的数据网格视图: IdentityNumber 、 Name 、 Date 。每列代表不同类型的值。identityNumner 是一个整数,Name 是一个字符串,日期是 DateTime。

我的目标是单击列的标题,然后将根据上述类型进行排序。如我所见,不做任何事情的自动排序是按字符串排序的。但我如何实现我的目标?

我找到了解决我的问题的方法。请检查下面的答案。

4

1 回答 1

0

为我的问题找到了解决方案:

在表单的 ctor 中,我注册了数据网格视图的 SortCompare 事件:

    DataGridView1.SortCompare += new DataGridViewSortCompareEventHandler(MyCustomSortFunction);

自定义函数 Iv'e build 是:

void MyCustomSortFunction(object sender, DataGridViewSortCompareEventArgs e)
    {
        try
        {
            // checks if the column's header that was pressed is the identity number - 
            // If so , sort as integer .

            if (e.Column.Name == "colIdentity") 
            {
                int a = Convert.ToInt32(e.CellValue1.ToString());
                int b = Convert.ToInt32(e.CellValue2.ToString());
                e.SortResult = a.CompareTo(b);
                e.Handled = true;
            }
            // checks if the column's header that was pressed is the date - 
            // If so , sort as DateTime .

            else if (e.Column.Name == "colHDate")
            {
                DateTime c = Convert.ToDateTime(e.CellValue1.ToString());
                DateTime d = Convert.ToDateTime(e.CellValue2.ToString());
                e.SortResult = c.CompareTo(d);
                e.Handled = true;
            }
        }
        catch
        { }
    }

希望我的回答对某人有所帮助:-) Shuki。

于 2013-09-04T13:09:26.493 回答