2016-12-12 39 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 = ...',應用程序接受它,但代碼沒有做任何事 –