DataGridView sorting with nulls in DateTime column

前端 未结 5 1285
猫巷女王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:45

    Updated Answer: After looking at your posted answer, I see that you're checking for DBNull.Value in the cells. That may be the source of your problem since DBNull.Value can't be cast to a DateTime. If you're programmatically adding the rows, try replacing DBNull.Value with null (Nothing).


    Original Answer: Try doing this for each column that holds DateTime data, preferably before any data is loaded:

    myDateTimeColumn.ValueType = GetType(DateTime)
    

    According to MSDN, the ValueType property is "used when filtering or sorting the columns with respect to the contents of their cells." So I would be sure to set it for any column that allows sorting.

    With this property set, the grid can be sorted on a column that has nulls and will force inserted/updated cells to be converted to DateTime.

提交回复
热议问题