在数据网格视图中对不同类型的列进行排序

时间:2013-09-04 08:25:43

标签: sorting datagridview datagridviewcolumn

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

我的目标是点击列标题,排序将根据上述类型完成。 没有做任何事情的自动排序是按字符串排序,我可以看到。 但我如何实现目标呢?

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

1 个答案:

答案 0 :(得分:0)

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

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

    DataGridView1.SortCompare += new DataGridViewSortCompareEventHandler(MyCustomSortFunction);

Iv'e构建的自定义功能是:

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。