DataGridView sorting with nulls in DateTime column

前端 未结 5 1287
猫巷女王i
猫巷女王i 2021-01-14 04:30

I\'ve got a DataGridView control in a Windows forms application. There are four columns with string data and three with DateTime data. I\'m adding the rows programmatically

5条回答
  •  梦谈多话
    2021-01-14 05:10

    Just to add some code to this question... I did the following to get sorting to work correctly for DateTime (and other non-string types) in the presence of nulls:

    public MyFormCTor() {
        ...
        m_dataGridView.SortCompare += MySortCompare;
        ...
    }
    
    ...
    
    static void MySortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        if (e.CellValue1 == e.CellValue2)
        {
            e.SortResult = 0;
            return;
        }
    
        if (e.CellValue1 == null)
        {
            e.SortResult = -1;
            return;
        }
    
        if (e.CellValue2 == null)
        {
            e.SortResult = 1;
            return;
        }
    
        e.SortResult = ((IComparable)e.CellValue1).CompareTo(e.CellValue2);
    }
    

提交回复
热议问题