如何忽略datagridview上的NULL条目

时间:2016-12-12 12:20:12

标签: .net vb.net datagridview null

我有一段代码从datagridview读取整数和日期值。一些k值包含空条目,并且我试图让应用程序忽略这些单元格,但我没有任何运气。该行上会弹出错误 j = datediff....

我尝试过使用if语句

If DataGridView1.Rows(e.RowIndex).Cells(k).Value IsNot Nothing Then 但它仍会产生错误,告诉我它无法将DBNull条目转换为date

我无法看到我做错了什么,所以任何帮助都会受到赞赏。

    For k = 8 To 52 Step 2

        Dim j As Integer

        If DataGridView1.Rows(e.RowIndex).Cells(k).Value IsNot Nothing Then

            j = DateDiff(DateInterval.Day, DataGridView1.Rows(e.RowIndex).Cells(k).Value, DataGridView1.Rows(e.RowIndex).Cells(k - 2).Value)

            If DataGridView1.Rows(e.RowIndex).Cells(k + 1).Value = 0 Then

                If j > 7 Then
                    DataGridView1.Rows(e.RowIndex).Cells(k - 1).Value = 6
                Else
                End If
            Else
            End If
        End If

    Next k

1 个答案:

答案 0 :(得分:0)

如果您希望在编译时识别可能的错误方面获得更多帮助,请在项目或文件中设置Option Strict On

  • NothingDbNull不一样。
  • Nothing
  • 类型的默认值
  • DbNull我们输入代表数据库NULL的值。
  • 只有DbNull.Value具有可比性。
For k = 8 To 52 Step 2
    Dim row As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
    If row.Cells(k).Value Is DBNull.Value Or row.Cells(k).Value Is Nothing Then Continue For

    Dim firstDate As Date = DirectCast(row.Cells(k).Value, Date)
    Dim secondDate As Date = DirectCast(row.Cells(k - 2).Value, Date)
    Dim difference As TimeSpan = firstDate - secondData

    If difference.Days > 7 AndAlso row.Cells(k + 1).Value = 0 Then
        row.Cells(k - 1).Value = 6
    End If

Next