DataGridView sorting with nulls in DateTime column

前端 未结 5 1174
猫巷女王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 04:54

    An easy solution is to add a "tonull" function, which you run the e.cellvalue1 and 2 through each time a comparison is made. If the value is "" then the value of the cell will be changed to 01/01/1001 if you want null values to appear first on the sort or 01/01/3001 or something ridiculously high if you want them to appear last on the sort.

    Private Sub dgvTable_SortCompare(ByVal sender As Object, ByVal e As DataGridViewSortCompareEventArgs) Handles dgvTable.SortCompare
    
        If e.Column.Index = 4 Then
    
            e.SortResult = System.DateTime.Compare(todatenull(e.CellValue1), todatenull(e.CellValue2))
    
        End If
    
        e.Handled = True
    End Sub
    
    
    Function todatenull(ByVal cellvalue)
        If cellvalue = "" Then
            Return "01/01/1001"
        Else
            Return cellvalue
        End If
    End Function
    

提交回复
热议问题