2016-12-12 37 views
0

我有一段代码从datagridview中读取整数和日期值。一些k值有空项目,我试图让应用程序忽略这些单元格,但我没有任何运气。错误就行了 j = datediff....如何忽略datagridview上的空条目

弹出我的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

因为'Nothing'不是'DbNull'。将'DbNull.Value'与条件 – Fabio

+0

相比较,if语句如'If Not IsDBNull(k)then''有效吗? –

回答

0

套装Option Strict On在你的项目,或者如果你想在编译时承认可能出现的错误得到更多的帮助文件。

  • NothingDbNull不一样。
  • Nothing是该类型的默认值
  • DbNull us类型,它代表数据库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 
+0

感谢您的回复!我现在明白了什么和DBNull之间的区别。我试着把你的代码放进去,但是在行'If Row.Cells(k).Value = DBNull.value Then Then For'时弹出一个错误:操作符'='没有为类型'Date'定义,并且类型'的DBNull'。有什么建议么? –

+0

'DataGridVIewCell.Value'返回'object'类型的值,所以使用'Is'关键字而不是'=' – Fabio

+0

感谢那部分工作。这个错误现在会弹出,显示为'dim firstdate as date ...'这一行,并且表示:对象引用未设置为对象的实例。 我把代码改回原来的'j = ...',应用程序接受它,但代码没有做任何事 –